halong
halong

Reputation: 70

macro in template class not work as I expected

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.

Upvotes: 0

Views: 521

Answers (1)

WARhead
WARhead

Reputation: 691

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();

Upvotes: 1

Related Questions