gpt4 book ai didi

c++ - 带有定义参数的嵌套定义C++

转载 作者:行者123 更新时间:2023-12-01 14:52:33 25 4
gpt4 key购买 nike

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

#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包含多个参数,因此 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__参数。

关于c++ - 带有定义参数的嵌套定义C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62178338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com