编译时开关生成基于结构中的字段数

Compile time switch generation based on number of fields in structure

本文关键字:结构 字段 开关 于结构 编译      更新时间:2023-10-16

如何在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

:

  1. BOOST_FUSION_DEFINE_STRUCT in boost::fusion文档

  2. size在boost::fusion文档

  3. 迭代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语句