0

I have a macro defined in a template class to use the real class Name. It may be not clear, and the code is below:


#include <iostream>

void Test_CB()
{
}

#define TEST_INTERFACE(xx) Test_##xx()


template <class T>
class CA
{
public:
    void Write()
    {
        TEST_INTERFACE(T);
    }
};

class CB : public CA<CB>
{

};


int main()
{
    CB b;
    b.Write();
    return 0;
}

I hope the result is class name:CB but on gcc, it output class name:T Is there any way to make it work as windows?


Maybe there is a problem with my presentation, I mean the visual c++ on windows and gcc on linux. I don't only want to get the type name. What I want is an identifier with part of the class name. I update the code.

halong
  • 70
  • 6
  • 1
    Does this answer your question? [C++ Get name of type in template](https://stackoverflow.com/questions/1055452/c-get-name-of-type-in-template) – Stephen Newell Apr 13 '21 at 03:54
  • Macros work at preprocessor time. It wouldn't really know what you've passed `T` as in that time because it hasn't even started compiling the program. It just stringifies the exact parameter it is given. – mediocrevegetable1 Apr 13 '21 at 03:57
  • A better solution would be to use [this template trick](https://stackoverflow.com/a/59522794/1678770) to extract the type-name by leveraging either `__PRETTY_FUNCTION__` or `__FUNCSIG__` – Human-Compiler Apr 13 '21 at 04:44
  • *"to make it work as windows"* I would say you also have `class name:T` on windows... – Jarod42 Apr 13 '21 at 07:49

1 Answers1

1

This is because template resolution happens during compile phase and pre-processor directives are resolved before compilation. Hence in this case when pre-processor is run, the macro receives the class as T hence the macro is replaced with "T".

What you need is this : typeid

add #include <typeinfo>

and replace the cout statement with:

std::cout << "class name:" << typeid(T).name();
WARhead
  • 643
  • 5
  • 17
  • 1
    `typeid(...).name()` is not guaranteed to yield the exact type-name as in source. In fact, `gcc` and `clang` both use this to output the *mangled name* instead -- which is often undesirable for logging. – Human-Compiler Apr 13 '21 at 04:43