Is there any way to evaluate decltype in a C ++ macro?
No, because macros are strictly evaluated before decltype .
As far as I know, there is no way to get the class name as a macro, stop completely. Any such method must be supported by a macro created by the compiler.
However, you can use typeid to get a malformed name (strictly speaking, a representation defined by an implementation), and then use compiler-specific tools to extract the unmarshaled name from it.
For example, GCC offers a demangling library for this.
Here is a minimal example of an online demo :
#define THIS_CLASS_NAME() demangled(typeid(*this).name()) std::string demangled(char const* tname) { std::unique_ptr<char, void(*)(void*)> name{abi::__cxa_demangle(tname, 0, 0, nullptr), std::free}; return {name.get()}; }
Using:
namespace foo { template <typename T> struct bar { bar() { std::cout << THIS_CLASS_NAME() << '\n'; } }; } int main() { foo::bar<int> b; }
Productivity:
foo::bar<int>
source share