Search code examples
c++c-preprocessordecltype

Is there any way to convert decltype to string in a macro?


Is there any way I can evaluate decltype in a C++ macro? My main motivation is to create a macro that is able to determine the type of this and convert it to a string.

If it's not possible to use decltype is there any other way a macro used inside a class declaration can get the type of the class as a string?


Solution

  • Is there any way I can evaluate decltype in a C++ macro?

    No, since macros are strictly evaluated before decltype.

    As far as I know there is no way to get the name of the class as a macro, full stop. Any such way would have to be supported by a compiler-generated macro.

    However, you can use typeid to get the mangled name (strictly speaking, an implementation-defined representation), and then use compiler-specific tools to retrieve the demangled name from that.

    For instance, GCC offers the demangling library to do this.

    Here’s a minimal example 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()};
    }
    

    Usage:

    namespace foo {
        template <typename T>
        struct bar {
            bar() { std::cout << THIS_CLASS_NAME() << '\n'; }
        };
    }
    
    int main() {
        foo::bar<int> b;
    }
    

    Yields:

    foo::bar<int>