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;
}
如果我传递一个具有多个参数的模板,这将不起作用,因为 <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>)
这篇关于如何将多参数模板传递给宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将多参数模板传递给宏?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
