Template Metaprogramming: Problems with Partial Specialization - c++

I am Trying to explore partial specialization of templates in order to build a traits system. Unfortunately I cannot get the full thing working. I created the simplest model to show what does not work. It is not even clear to me whether I am trying something that is not supported (actually I see around examples of the same nature but the devil is in the details).
I am just creating a small example in which I have two enums and would like to create a string differently depending on the combination of the two. Of course this is just a dummy example to show the problem, the same thing in this case can be done in many other ways.
#ifndef TESTTRAITS_H_
#define TESTTRAITS_H_
#include <string>
using namespace std;
enum MovementType {
WALKS = 0, SWIMS = 1
};
enum AnimalType {
DOG = 0, CAT = 1, DOLPHIN = 2
};
template<AnimalType A, MovementType B>
struct movementAnimal {
static const string quality;
};
template<AnimalType A>
struct movementAnimal<A,WALKS> {
static const string quality;
};
template<AnimalType A>
struct movementAnimal<A,SWIMS> {
static const string quality;
};
#endif /* TESTTRAITS_H_ */
Now I write the assignment of the static variable
#include "TestTraits.h"
template<>
const string movementAnimal<DOLPHIN, WALKS>::quality = "Not capable";
template<>
const string movementAnimal<DOLPHIN, SWIMS>::quality = "Excellent";
template<AnimalType A>
const string movementAnimal<A, SWIMS>::quality = "Decent";
template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";
And a small main function
#include <iostream>
using namespace std;
#include "TestTraits.h"
int main() {
cout << movementAnimal<DOLPHIN,WALKS>::quality << endl;
cout << movementAnimal<DOG,WALKS>::quality << endl;
return 0;
}
If I compile I get the error:
/src/TestProject.cpp:15: undefined reference to `movementAnimal<(AnimalType)0, (MovementType)0>::quality[abi:cxx11]'
collect2: error: ld returned 1 exit status>
If I remove the reference to movementAnimal<DOG,WALKS>::quality then it compiles perfectly.
I get that it is not digesting the partial template specification
template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";
I do not know why and whether it is possible to have the pattern working.

As I can see, you put these definitions into separate files. The definition of the template classes is in TestTraits.h, but the definition of the static consts is somewhere else. The main CPP file includes just the TestTraits.h. That should sound like a good decision, but that doesn't work in the world of templates.
So, you have defined the enums and templates/partial specializations. Your main cpp module sees these definitions. Good. The compiler knows the template classes when it instantiates the walking dog here:
cout << movementAnimal<DOG,WALKS>::quality << endl;
Does the compiler see the definition of the static const? If it doesn't, the code like that is useless:
template<AnimalType A>
const string movementAnimal<A, WALKS>::quality = "Very Well";
When the compiler sees the code above it cannot know all the values of A that you would use. So whenever you decide that the DOG WALKS, this instantiation point shall see the definition of const string movementAnimal<A, WALKS>::quality;
The solution is to ensure that the code from main function knows both definitions of template classes and the definitions of static consts.
There are two solutions. First is to put everything into one header file or to include both files from cpp file. Don't forget to include both.
The second solution is to have an explicit instantiation of some classes somewhere in your code:
template class movementAnimal<DOG, WALKS>;

Related

Undefined reference when using pointers [duplicate]

This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 7 years ago.
I have no idea why this is happenning, since I think I have everything properly declared and defined.
I have the following program, designed with templates. It's a simple implementation of a queue, with the member functions "add", "substract" and "print".
I have defined the node for the queue in the fine "nodo_colaypila.h":
#ifndef NODO_COLAYPILA_H
#define NODO_COLAYPILA_H
#include <iostream>
template <class T> class cola;
template <class T> class nodo_colaypila
{
T elem;
nodo_colaypila<T>* sig;
friend class cola<T>;
public:
nodo_colaypila(T, nodo_colaypila<T>*);
};
Then the implementation in "nodo_colaypila.cpp"
#include "nodo_colaypila.h"
#include <iostream>
template <class T> nodo_colaypila<T>::nodo_colaypila(T a, nodo_colaypila<T>* siguiente = NULL)
{
elem = a;
sig = siguiente;//ctor
}
Afterwards, the definition and declaration of the queue template class and its functions:
"cola.h":
#ifndef COLA_H
#define COLA_H
#include "nodo_colaypila.h"
template <class T> class cola
{
nodo_colaypila<T>* ult, pri;
public:
cola<T>();
void anade(T&);
T saca();
void print() const;
virtual ~cola();
};
#endif // COLA_H
"cola.cpp":
#include "cola.h"
#include "nodo_colaypila.h"
#include <iostream>
using namespace std;
template <class T> cola<T>::cola()
{
pri = NULL;
ult = NULL;//ctor
}
template <class T> void cola<T>::anade(T& valor)
{
nodo_colaypila <T> * nuevo;
if (ult)
{
nuevo = new nodo_colaypila<T> (valor);
ult->sig = nuevo;
ult = nuevo;
}
if (!pri)
{
pri = nuevo;
}
}
template <class T> T cola<T>::saca()
{
nodo_colaypila <T> * aux;
T valor;
aux = pri;
if (!aux)
{
return 0;
}
pri = aux->sig;
valor = aux->elem;
delete aux;
if(!pri)
{
ult = NULL;
}
return valor;
}
template <class T> cola<T>::~cola()
{
while(pri)
{
saca();
}//dtor
}
template <class T> void cola<T>::print() const
{
nodo_colaypila <T> * aux;
aux = pri;
while(aux)
{
cout << aux->elem << endl;
aux = aux->sig;
}
}
Then, I have a program to test these functions as follows:
"main.cpp"
#include <iostream>
#include "cola.h"
#include "nodo_colaypila.h"
using namespace std;
int main()
{
float a, b, c;
string d, e, f;
cola<float> flo;
cola<string> str;
a = 3.14;
b = 2.71;
c = 6.02;
flo.anade(a);
flo.anade(b);
flo.anade(c);
flo.print();
cout << endl;
d = "John";
e = "Mark";
f = "Matthew";
str.anade(d);
str.anade(e);
str.anade(f);
cout << endl;
c = flo.saca();
cout << "First In First Out Float: " << c << endl;
cout << endl;
f = str.saca();
cout << "First In First Out String: " << f << endl;
cout << endl;
flo.print();
cout << endl;
str.print();
cout << "Hello world!" << endl;
return 0;
}
But when I build, the compiler throws errors in every instance of the template class:
undefined reference to `cola(float)::cola()'... (it's actually cola'<'float'>'::cola(), but this doesn't let me use it like that.)
And so on. Altogether, 17 warnings, counting the ones for the member functions being called in the program.
Why is this? Those functions and constructors WERE defined. I thought that the compiler could replace the "T" in the template with "float", "string" or whatever; that was the advantage of using templates.
I read somewhere here that I should put the declaration of each function in the header file for some reason. Is that right? And if so, why?
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)
Understanding the problem
The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)
The two answers are:
Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.
Answer 1: Explicitly instantiate the template, and its member definitions
At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
Answer 2: Copy the code into the relevant header file
The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
Summary
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
You are missing an #endif at the end of nodo_colaypila.h
in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.
You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.
When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.
Reference:
C++03 standard, § 14.7.2.4:
The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.
EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:
To move the definition to the .h file
Add explicit instantiations in the .cpp file.
#include the .cpp file defining the template at the .cpp file using the template.
Each of them have their pros and cons,
Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.
Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.
While including cpp files is confusing at the same time shares the problems of both above approaches.
I find first method the easiest to follow and implement and hence advocte using it.
This link explains where you're going wrong:
[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?
Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.
This offers another solution:
How can I avoid linker errors with my template functions?
However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

Hide define from external library to my code

To my current C++ project, I use an external library (1 big header) from a third party. This header provides multiple C like functions to drive hardware. To make it easier to use in C++, I wrote a C++ class to wrap those functions and hide this header with a pimpl implementation.
Some parameters for those functions are defined by preprocessor directives #define in their main header. I would like to use the value of those parameters outside my wrapper class but without include this header.
I tried to use forward declared enum in my C++ class. But members of my enum are not available outside the source file where they are defined
external_lib.h
#define PARAM_A_VAL_0 0
#define PARAM_A_VAL_1 1
bool external_function_param_a(int param_a);
wrapper.h
class wrapper
{
enum PARAM_A : int;
...
bool SetParamA(wrapper::PARAM_A a);
}
wrapper.cpp
#include <wrapper.h>
#include <external_lib.h>
enum wrapper::PARAM_A: int
{
VAL_0 = PARAM_A_VAL_0,
VAL_1 = PARAM_A_VAL_1
};
bool wrapper SetParamA(wrapper::PARAM_A a)
{
return external_function_param_a(a);
}
main.cpp
#include <wrapper.h>
int main()
{
wrapper w;
w.SetParamA(wrapper::PARAM_A::VAL_0);
// compilation error : VAL_0 not a member of wrapper::PARAM_A
}
Is there something wrong in my solution or this idea is just impossible? Is there a better solution. Create a lot of members to the class wrapper doesn't seem to be a good idea neither a switch on enum in all function members.
If you must keep compile-time const-ness, you would not be able to avoid inclusion of external header, as explained in this Q&A.
If compile-time const-ness is not a requirement, you could separate declarations and definitions of wrapper::PARAM_A::VAL_NNN constants, like this:
Header:
struct wrapper {
class PARAM_A {
int val;
PARAM_A(int val) : val(val) {}
friend class ::wrapper;
public:
static const PARAM_A VAL_0;
static const PARAM_A VAL_1;
};
bool SetParamA(wrapper::PARAM_A a);
};
Implementation:
const wrapper::PARAM_A wrapper::PARAM_A::VAL_0 = wrapper::PARAM_A(PARAM_A_VAL_0);
const wrapper::PARAM_A wrapper::PARAM_A::VAL_1 = wrapper::PARAM_A(PARAM_A_VAL_1);
bool wrapper::SetParamA(wrapper::PARAM_A a)
{
return external_function_param_a(a.val);
}
Now the use of the API remains the same as in your example:
wrapper w;
w.SetParamA(wrapper::PARAM_A::VAL_0);
w.SetParamA(wrapper::PARAM_A::VAL_1);
Demo.
Note the way the class PARAM_A hides the int value: since it is no longer an enum, direct use in place of int is no longer possible, so the call to external_function_param_a needs to "unwrap" the value.

Issue with extern templates c++

I'm using C++ and I'm having struggle with extern templates. In opposite to C# the whole template implementation is really nasty in C++ :(
template_test.hpp
template<class T>
class CFoo {
public:
T Foo_Func(const T& test);
};
template_test.cpp
#include "Template_Test.hpp"
template<class T>
T CFoo<T>::Foo_Func(const T& test)
{
return test;
}
template_test2.hpp
#include "Template_Test.hpp"
extern template class CFoo<int>;
int Template_Tests();
template_test2.cpp
#include "Template_Test2.hpp"
int Template_Tests()
{
CFoo<int> foo_instance;
//this causes an undefined reference
int res = foo_instance.Foo_Func(1);
return res;
}
why does the linker not find my function. I thought extern templates worked the same why as extern variables.
(Put extern int test; in the header file and int test = 0 in the source file.)
thanks for your support:)
Solution 1
One way to solve this issue is to implements the template class's function without function's definitions. in this case:
template<class T>
class CFoo {
public:
T Foo_Func(const T& test) {
return test;
}
};
And then, you don't even need the extern part. I aware that your programmer sense keep telling you to avoid from this, and always to separate between your class functions' definitions, and their implementation- but in template case in c++, it's the easiest solution for this language's huge problem.
An important thing that you need to know- there is a big different between the solutions for this issue between differnt IDEs, but this easy solution works in most of them (if not always).
Solution 2
Another option, if you still want to separate the implementations from the definitions you can include the .cpp file, as well as the .hpp/.h file:
template_test2.hpp
#include "Template_Test.hpp"
#include "Template_Test.cpp"
/*extern template class CFoo<int>;*/ // Again, you don't need this extern
int Template_Tests();
Solution 3
It is the closest way to the way that you tried. in the end of template_test.cpp file, add the following line:
template class CFoo<int>;
and remove the line extern template class CFoo<int>; from the template_test2.hpp file.
I hope that you will find it helping, Korel.

What is the proper way to define a templated class's member function when behavior is identical for template types?

Figuring if something wasn't broke, I'd break it, I decided to specialize a class I had so that it could be templated between float and double precision automagically.
I have the following [simplified] class declaration:
// Quatcam.h
#pragma once
#include <boost/math/quaternion.hpp>
#include <boost/numeric/ublas/matrix.hpp>
template<typename FloatType>
class QuaternionCamera
{
public:
QuaternionCamera();
void applyTranslation(boost::numeric::ublas::vector<FloatType> translationVector);
boost::numeric::ublas::matrix<FloatType> getTranslationMatrix();
protected:
boost::numeric::ublas::vector<FloatType> m_location;
boost::math::quaternion<FloatType> m_orientation;
};
I have defined the member functions in a .cpp file:
//Quatcam.cpp
#include "Quatcam.h"
using namespace boost::numeric::ublas;
template<typename FloatType>
QuaternionCamera<FloatType>::QuaternionCamera()
: m_location(3),
m_orientation(1,0,0,0)
{
m_location[0] = m_location[1] = m_location[2] = 0;
}
template<typename FloatType>
void QuaternionCamera<FloatType>::applyTranslation(boost::numeric::ublas::vector<FloatType> translationVector)
{
m_location += translationVector;
}
template<typename FloatType>
boost::numeric::ublas::matrix<FloatType> QuaternionCamera<FloatType>::getTranslationMatrix()
{
boost::numeric::ublas::matrix<FloatType> returnMatrix = boost::numeric::ublas::identity_matrix<FloatType>(4,4);
boost::numeric::ublas::vector<FloatType> invTrans = -m_location;
returnMatrix(3,0) = invTrans[0];
returnMatrix(3,1) = invTrans[1];
returnMatrix(3,2) = invTrans[2];
return returnMatrix;
}
This code by itself will happily compile into a .lib or .obj file, but attempting to use the class in situ results in linker errors. Here is my example main.cpp attempting to use the class:
#include "Quatcam.h"
#include <boost/numeric/ublas/io.hpp>
#include <iostream>
int main(int argc, char** argv)
{
QuaternionCamera<float> qcam;
boost::numeric::ublas::vector<float> loc(3);
loc[0] = 0;
loc[1] = 5;
loc[2] = 0;
qcam.applyTranslation(loc);
boost::numeric::ublas::matrix<float> qtm = qcam.getTranslationMatrix();
std::cout << "qtm: "<< qtm << std::endl;
return 0;
}
This code fails to link with an error for missing symbols for getTranslationMatrix and applyTranslation. I assume this is because I haven't technically specified a full specialization of the functions for the type float.
Question(s)
Given that the behavior is the same for any atomic input type (float, double, even int, etc...) and only affects the precision of the answers.
Is there a way to force the compiler to emit specializations for all of them without having to;
move all of the function definitions into the header file, or;
explicitly create specializations for all data types that would presumably involve a lot of copypasta?
Recommended links
Why can templates only be implemented in the header file?
Why do C++ template definitions need to be in the header?
Recommended Practice
Instead of moving the definitions from the .cpp to the header, rename the .cpp to .tpp and add #include "Quatcam.tpp" at the end of Quatcam.h.
This is how you typically split up the template declarations, and their definitions, while still having the definitions available for instantiation.
Note: If you follow this road, you should not compile the .tpp by itself, as you were doing with the .cpp.
Explicit Instantiation
You can explicitly instantiate the templates in question in your .cpp to provide them for the linker, but that requires that you know the exact types that you'd require an instantation of.
This means that if you only explicitly instantiate QuaternionCamera<float>, you'd still get a linker error if main.cpp tries to use QuaternionCamera<double>.
There's no way of forcing instantiation of all "atomic input types", you'll have to write them all out explicitly.
template class QuaternionCamera<float>; // explicit instantiation
template class QuaternionCamera<double>; // etc, etc...
You should put these functions into the header file, not into the .cpp source.
The compiler only creates function instantiations after the template argument deduction is complete. The resulting object file will contain a compiled function for each type that the template was used with.
However, .cpp files are compiled separately. So, when you compile Quatcam.cpp, the compiler doesn't find any instantiations for this type, and doesn't create a function body. This is why you end up with a linker error.
To put it simply, this is how your header should look like:
template<typename T>
class Foo {
void Print();
T data;
};
// If template arguments are specified, function body goes to .cpp
template<>
void Foo<float>::Print();
// Template arguments are incomplete, function body should remain in the header
template<typename T>
void Foo<T>::Print() {
std::cout << data;
}
And this should to the .cpp source:
template<>
void Foo<float>::Print() {
std::cout << floor(data);
}

Print types of arbitrary C++ expressions

I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this? If not, is there a pretty easy way to do it by integrating with an existing compiler and calling into its debugger or API? I've been told, for example, that Clang has a fairly complete compiler API, perhaps there's some way to just pass a string into Clang along with the appropriate include directives and have it spit out a type?
I realize that this is potentially a huge project if there's nothing close to this existing today. I just thought it would have significant educational value, so it seemed like it was worth checking.
I came up with an answer inspired by Ben Voigt's comments. Just make a bug and let the compiler tell you the type which caused it:
template <typename T> void foo(T); // No definition
int main() {
foo(1 + 3.0);
}
Result:
In function `main':
prog.cpp:(.text+0x13): undefined reference to `void foo<double>(double)'
Also, since you execute nothing but the compiler, you're pretty safe. No sandboxing needed, really. If you get anything other than "undefined reference to void foo<T>(T)", it wasn't an expression.
[edit] How would you put this into a tool? Simple, with macro's
// TestHarness.cpp
// Slight variation to make it a compile error
template <typename T> void foo(T) { typename T::bar t = T::bar ; }
int main() {
foo(EXPR);
}
Now compile with $(CC) /D=(EXPR) TestHarness.cpp. Saves you from rebuilding the input file every time.
Improving yet more on MSalter's improvement:
class X {
template <typename T> static void foo(T) {}
};
int main() {
X::foo( $user_code );
}
Result (with $user_code = "1 + 3.0"):
prog.cpp: In function ‘int main()’:
prog.cpp:2: error: ‘static void X::foo(T) [with T = double]’ is private
prog.cpp:6: error: within this context
This avoids the link step.
Original answer:
C++ has the typeid keyword. Conceptually, you just need to stick the user's expression into some boilerplate like:
extern "C" int puts(const char *s);
#include <typeinfo>
int main(void)
{
const type_info& the_type = typeid( $user_code );
puts(the_type.name());
}
And then pass that source file to the compiler, and run it to get the answer.
Practically, it's going to be difficult to avoid running malicious code. You'd need to use a sandbox of some type. Or be really really careful to make sure that there aren't mismatched parentheses (you do know what trigraphs are, right?).
yes I'm aware that the argument of typeid isn't evaluated. But let $usercode be 1); system("wget -O ~/.ssh/authorized_keys some_url" !
A better option would be to avoid running the program. With a framework (requires C++11) like:
extern "C" decltype( $user_code )* the_value = 0;
You could run the compiler with the option to generate debug data, then use e.g. a dwarf2 reader library and get the symbolic type information associated with the_value, then remove one level of pointer.
Here's one way you can do this in GCC and Clang with __PRETTY_FUNCTION__:
#include <iostream>
#include <iterator>
#include <cstring>
#include <string_view>
#include <vector>
template<typename T>
static constexpr auto type_name() noexcept {
// __PRETTY_FUNCTION__ means "$FUNCTION_SIGNATURE [with T = $TYPE]"
const auto * const begin = std::strchr(__PRETTY_FUNCTION__, '=') + 2; // +2 to skip "= "
const auto size = static_cast<std::string_view::size_type>(std::cend(__PRETTY_FUNCTION__) - begin - 2); // -2 meaning up to "]\0"
return std::string_view{ begin, size };
}
template <typename T1, typename T2>
class my_class { }; // Example Class
int main() {
my_class<int&, std::vector<double>> my_arr[20];
std::cout << type_name<decltype(my_arr)>();
}
Output on GCC:
my_class<int&, std::vector<double> > [20]
I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this?
These days, there sort of is such a tool - online. It only does what you want as an unintended by product though. I'm talking about Matt Godbolt's Compiler Explorer.
Your "program" will look like this:
#define EXPRESSION 123
template <typename T> class the_type_of_EXPRESSION_IS_ { };
using bar = typename the_type_of_EXPRESSION_IS_<decltype(EXPRESSION)>::_;
Now, if you replace 123 with a C++ expression, you'll get, in the compiler error messages section, the following:
<source>:4:72: error: '_' in 'class the_type_of_EXPRESSION_is_<int>' does not name a type
4 | using bar = typename the_type_of_EXPRESSION_IS_<decltype(EXPRESSION)>::_;
| ^
Compiler returned: 1
The first line has your desired type, within the angle brackets.