Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

c++ - How to pass multi-argument templates to macros?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...