编译时开关生成基于结构中的字段数
Compile time switch generation based on number of fields in structure
如何在c++ 03中获得所选结构的成员数?我正在试验BOOST_FUSION_ADAPT_STRUCT
,但我没有得到任何工作示例。
我想在编译时生成switch语句,其中每个成员将有一个case。比如说我们有一个有3个成员的struct那么我要生成这个switch
switch(val)
{
case 0:
break;
case 1:
break;
case 2:
break;
}
在每条语句中,我将使用一些参数调用模板函数。
我怎么能做这样的事情?
如果您使用BOOST_FUSION_DEFINE_STRUCT
定义结构体本身,boost将以这样一种方式生成结构体,您可以轻松地执行以下操作:
#include <boost/fusion/include/define_struct.hpp>
#include <boost/fusion/include/size.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <iostream>
#include <string>
// demo::employee is a Fusion sequence
BOOST_FUSION_DEFINE_STRUCT(
(),
employee,
(std::string, name)
(int, age))
int main() {
employee e{"hey", 5};
int x = boost::fusion::size(e);
std::cerr << x << std::endl;
auto print = [] (auto v) { std::cerr << v << std::endl; };
boost::fusion::for_each(e, print);
return 0;
}
我修改了上面的代码,以遍历结构体的成员并应用泛型函数。这在功能上似乎和你假设的case语句做的是一样的。
你不能传递这段代码生成的"2"来增强预处理器宏的原因是预处理器首先运行,在代码之前,你不能在编译时或运行时将生成的数字输入预处理器。
程序打印:
2
hey
5
:
BOOST_FUSION_DEFINE_STRUCT in boost::fusion文档
size在boost::fusion文档
迭代Boost fusion::vector
经过长时间的搜索,阅读和找到这篇文章。我设法迭代成员从0到count - 1(从创建switch语句很容易)。
#include <iostream>
#include <string>
#include <vector>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/fusion/include/define_struct.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <boost/preprocessor/seq/cat.hpp>
struct MyStruct
{
int x;
int y;
};
#define GO(r, data, elem) elem
#define SEQ1 ((int,x))((int,y))
BOOST_FUSION_ADAPT_STRUCT(
MyStruct,
BOOST_PP_SEQ_FOR_EACH(GO, ,SEQ1)
)
#define PRINT(unused, number, data)
std::cout << number << std::endl;
int main()
{
BOOST_PP_REPEAT(BOOST_PP_SEQ_SIZE(SEQ1), PRINT, "data")
}
现在BOOST_PP_REPEAT
可以创建case语句
相关文章:
- 将结构字段的类型展开为可变模板参数
- 结构字段名称与 GDB 中的 STL 数组冲突
- 初始化派生结构的基部分/意外打包派生结构字段以对齐基结构的间隙
- 如何为结构字段动态分配字符空间
- 实例化时结构字段中的默认值
- 如何使用函数的输出初始化 const 数组结构字段?
- 无法访问 Arduino 结构字段。错误"退出状态 1。xxxx 不命名类型"
- 列出常量和数组结构字段的初始化
- 如何使用 gtest 构造检查存储在向量中的结构(字段)?
- 将带有结构字段的结构从C 返回到C#PINVOKE
- 嵌套结构字段的 clang 格式规则
- 如何匹配通过引用传递给模拟函数的结构字段
- 在C 中获得相反的结构字段
- 如何为我的 Vulkan 类创建此通用数据结构字段
- 如何初始化结构字段 std::map<std::string, std::string>称为参数
- 在编译时使用模板在跨结构字段中迭代
- 正在取消引用自定义结构字段的迭代器
- 结构字段上的智能指针
- 使用C预处理器在结构字段上进行迭代
- 结构字段的默认初始化行为