可变参数宏和参数包扩展
Variable arguments macro and parameter pack expansion
在以下示例代码中,我想将带有变量参数的MACRO_EXPANSION
和{...}
使用EnumTypes
对象列表。但是,我无法使这个想法起作用。(ps。代码结构看起来不太好,但我需要它:)
#include <iostream>
#include <utility>
#include <initializer_list>
enum class EnumOneTypes {
One0,
One1
};
enum class EnumTwoTypes {
Two0,
Two1
};
struct EnumTypes {
EnumOneTypes one;
EnumTwoTypes two;
};
void do_something(std::initializer_list<EnumTypes> il) {
std::cout << "Do something" << std::endl;
}
// Need this struct to forward arguments
struct Register {
template <typename... TArgs>
Register(TArgs&&... args) {
do_something(std::forward<TArgs>(args)...);
//also do other things after do_something, omit here
// ...
}
};
// Use this macro to define global static objects
#define MACRO_EXPANSION(name, ...)
static struct Register name(__VA_ARGS__)
MACRO_EXPANSION(
register_two,
{EnumOneTypes::One0, EnumTwoTypes::Two0},
{EnumOneTypes::One1, EnumTwoTypes::Two1}
);
MACRO_EXPANSION(
register_three,
{EnumOneTypes::One0, EnumTwoTypes::Two0},
{EnumOneTypes::One1, EnumTwoTypes::Two1},
{EnumOneTypes::One0, EnumTwoTypes::Two1}
);
int main() {
std::cout << "Test the usage of this macro" << std::endl;
return 0;
}
- variadic模板不能自动为
std::initializer_list
。因此,让我们用牙套包裹variadic参数。
struct Register {
template <typename... TArgs>
Register(TArgs&&... args) {
do_something({std::forward<TArgs>(args)...}); // Make params to be initializer List
//also do other things after do_something, omit here
// ...
}
};
- 由于
Register
构造函数已被模板,因此编译器似乎无法推断出哪种{EnumOneTypes::One0, EnumTwoTypes::Two0}
类型。因此,让我们指定其类型:
MACRO_EXPANSION(
register_two,
EnumTypes{EnumOneTypes::One0, EnumTwoTypes::Two0},
EnumTypes{EnumOneTypes::One1, EnumTwoTypes::Two1}
);
应用这两个后,它将成功编译并以输出运行:
Do something
Do something
Test the usage of this macro
我在Godbolt中进行了测试。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 扩展可变参数模板中的变量名称
- 扩展C++生成的代码的模板参数类型名称
- 将元组类型扩展为可变参数模板?
- 嵌套参数包扩展失败
- 模板参数部分中有关包扩展的一些混淆
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 如何使用 std::forward 精确地评估参数包的扩展?
- 参数包没有扩展'...'即使...被使用
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- 如何"unzipping"扩展参数包模式?
- 可变参数函数参数包扩展
- c++非类型参数包扩展
- 如何使用自己的参数扩展 PointNormal 类?
- C 功能参数扩展了多个类
- 模板模板参数 - 扩展为 std::array
- C/C++ 如何将宏参数扩展为引号之间的文本
- 没有类型定义的可变参数扩展器
- 可变参数扩展是否可以用作逗号运算符调用链
- Template可变模板的模板参数扩展