带有多个参数的c++宏和模板错误

C++ macro and template with multiple arguments error

本文关键字:错误 c++ 参数      更新时间:2023-10-16

我用这个简单的(无用的)代码来演示这个问题:

template<typename _Tx, typename _Ty>
struct foo{};
#define TO_STRING(Type) #Type
int main()
{
    std::string sInt = TO_STRING(int);
    std::string sfoo1 = TO_STRING(foo<int, float>); //warning and unexpected value - "foo<int"
    std::string sfoo2 = TO_STRING((foo<int, float>)); //no warning, still unexpected value "(foo<int, float>)"
}

是否有一种方法可以将带有多个参数的模板传递给宏而不使用() ?

这可能不是理想的,但我认为它可以在几乎任何编译器上工作(如果你找到一个不这样做的编译器,它很容易在不改变接口的情况下简化):

#define TO_STRING1(_a_) #_a_
#define TO_STRING2(_a_, ...) #_a_ ", " TO_STRING1(__VA_ARGS__)
#define TO_STRING3(_a_, ...) #_a_ ", " TO_STRING2(__VA_ARGS__)
#define TO_STRING4(_a_, ...) #_a_ ", " TO_STRING3(__VA_ARGS__)
唯一的缺点是你必须自己计算逗号,例如:
std::string sInt = TO_STRING1(int);
std::string sfoo = TO_STRING2(foo<int, float>);