宏可以接受列表初始化作为参数吗?

时间:2014-04-13 15:18:02

标签: c++ c++11 macros arguments

有什么方法可以使下面的代码有效吗?它目前给出以下错误:

error: too many arguments provided to function-like macro invocation
         X({1,2,3});
                             ^

代码:

#include <stdio.h>
#define X(a) a,

int main()
{
    mystruct = X({1,2,3}));
}

我尝试使用templates,但到目前为止我知道(我对C ++有点新鲜)templates不足以实现类似X宏的功能。正如您可能已经注意到的那样,我正在寻找的是实现类似X宏的东西。只要在编译时知道所有内容,其他人也非常欢迎这样做。

1 个答案:

答案 0 :(得分:1)

does the trick

#define X(...) __VA_ARGS__

struct mystruct {
    int a,b,c;
};

int main() {
    mystruct s = X({1,2,3});
}

variation

#define X(...) {__VA_ARGS__}

struct mystruct {
   int a,b,c;
};

int main() {
   mystruct s = X(1,2,3);
}