嵌套定义具有定义的参数c ++

nested defines with defined parameters c++

这是我的代码的一个较小的复制器:

#include <vector>
#include <iostream>

struct mystruct {
    int a;
    int param1;
    int param2;
};

#define mycase 5, 5

#define mytest_1(test) \
    mystruct{ 1, test }, \
    mystruct{ 2, test }

#define mytest_2(test) \
    mystruct{ 3, test }, \
    mystruct{ 4, test }

#define mytest_all(test) \
    mytest_1(test), \
    mytest_2(test)

void check(std::vector<mystruct> a) {
    for (int i = 0; i < a.size(); i++) {
        std::cout << i << ": " << a[i].a << " " << a[i].param1 << " " << a[i].param2 << std::endl;
    }
}

int main() {
    check(std::vector<mystruct>{mytest_1(mycase), mytest_2(mycase)});   // works fine
    check(std::vector<mystruct>{mytest_all(mycase)});                   // doesn't work

    return 0;
}

编译器产生以下错误(我使用的是 g++ 7.4.0):

test.cpp:32:50: error: macro "mytest_1" passed 2 arguments, but takes just 1
     check(std::vector<mystruct>{mytest_all(mycase)});
...                                                  ^
test.cpp:21:5: error: 'mytest_1' was not declared in this scope
     mytest_1(test), \
     ^
test.cpp:32:33: note: in expansion of macro 'mytest_all'
     check(std::vector<mystruct>{mytest_all(mycase)});
                                 ^~~~~~~~~~
... # some more errors

据我从错误消息中了解到,这是因为 #define mycase 5, 5 由不止 1 个参数组成,所以 mytest_all 被展开成这样: mytest_1(5, 5).

有没有办法以另一种方式定义 mytest_all 以使其工作?考虑到我无法更改 mytest_1。谢谢!

解决方法如下:

#define IDENTITY(...) __VA_ARGS__

#define mytest_all(test) \
    mytest_1(IDENTITY(test)), \
    mytest_2(IDENTITY(test))

但是如果您可以更改 mytest_12,更好的选择是让它们使用 .../__VA_ARGS__ 参数。