如何在C ++ 03中获取所选结构的成员编译时间?我正在尝试BOOST_FUSION_ADAPT_STRUCT
,但我没有得到任何有效的例子。
我想在编译时生成switch语句,每个成员都会有一个case。所以假设我们有3个成员的结构然后我想生成这个开关:
switch(val)
{
case 0:
break;
case 1:
break;
case 2:
break;
}
在每个语句中,我将使用一些参数调用模板函数。其中一个参数是结构的成员。
我怎么能这样做?
答案 0 :(得分:1)
如果使用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;
}
我修改了上面的代码,也迭代了struct的成员并应用了泛型函数。看起来这个功能与你的假设案例陈述的功能相同。
您无法传递此代码生成的“2”以增强预处理器宏的原因是因为预处理器首先在代码之前运行,您无法在编译时或运行时将数字生成到预处理器中。
此程序打印:
2
hey
5
请参阅:
答案 1 :(得分:1)
经过长时间的搜索,阅读和找到this article。我设法迭代成员从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
可能会创建案例陈述。