Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say I have a macro like this:

#define SET_TYPE_NAME(TYPE, NAME) 
    template<typename T>          
    std::string name();           
                                  
    template<>                    
    std::string name<TYPE>() {    
        return NAME;              
    }

This won't work if I pass it a template that has more than one parameter, because the comma in the <int, int> is interpreted as separating the macro arguments, not the template arguments.

SET_TYPE_NAME(std::map<int, int>, "TheMap")
// Error: macro expects two arguments, three given

This problem seems to be solved by doing this:

SET_TYPE_NAME((std::map<int, int>), "TheMap")

But now another problem arises, one that I really did not expect:

 template<>
 std::string name<(std::map<int, int>)>()
 // template argument 1 is invalid

It seems that the extra parentheses make the template argument invalid. Is there any way around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

Besides typedef, you could switch the order of the arguments and use variadic macros (requires C99 or C++11-compatible compiler):

#define SET_TYPE_NAME(NAME, ...) 
template<typename T>          
std::string name();           
                              
template<>                    
std::string name<__VA_ARGS__>() {    
    return NAME;              
}

...

SET_TYPE_NAME("TheMap", std::map<int, int>)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...