如何将多参数模板传递到宏? [英] How to pass multi-argument templates to macros?

查看:122
本文介绍了如何将多参数模板传递到宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的宏:

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

如果我传递的模板有更多因为< int,int> 中的逗号被解释为将宏参数分开,而不是模板参数。

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?

推荐答案

除了 typedef 切换参数的顺序并使用可变宏(需要C99或C ++ 11兼容的编译器):

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

这篇关于如何将多参数模板传递到宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆