问题描述
有可能在C ++中迭代一个Struct或类来查找其所有成员?例如,如果我有结构a和类b:
struct a
{
int a ;
int b;
int c;
}
class b
{
public:
int a;
int b;
private:
int c;
}
是否可以循环来说说得到一个打印语句:Struct a has int name a,b,corClass b has int named a,b,c
一些方法来做到这一点,但你需要使用一些宏来定义或适应结构。
您可以使用来定义这样的结构:
struct A
{
REFLECTABLE
(
(int)a,
(int)b,
(int)c
)
然后你可以遍历字段并打印每个值,如下所示:
struct print_visitor
{
template< class FieldData>
void operator()(FieldData f)
{
std :: cout< f.name()<< =<< f.get()<< std :: endl;
}
};
template< class T>
void print_fields(T& x)
{
visit_each(x,print_visitor());
}
A x;
print_fields(x);另一种方法是将struct作为一个融合序列(参见)。这里有一个例子: struct A
{
int a;
int b;
int c;
};
BOOST_FUSION_ADAPT_STRUCT
(
A,
(int,a)
(int,b)
b)
然后您也可以使用以下命令打印字段:
struct print_visitor
{
template< class Index,class C>
void operator()(Index,C& c)
{
std :: cout< boost :: fusion :: extension :: struct_member_name< C,Index :: value> :: call()
< =
<< boost ::: fusion :: at< Index>(c)
< std :: endl;
}
};
模板< class C>
void print_fields(C& c)
{
typedef boost :: mpl :: range_c< int,0,boost :: fusion :: result_of :: size< C& :: value>范围;
boost :: mpl :: for_each< range>(boost :: bind< void>(print_visitor(),boost :: ref(c),_1)
}
Is it possible in C++ to iterate through a Struct or Class to find all of its members? For example, if I have struct a, and class b:
struct a
{
int a;
int b;
int c;
}
class b
{
public:
int a;
int b;
private:
int c;
}
Would it be possible to loop them to say get a print statement saying "Struct a has int named a, b, c" or "Class b has int named a, b, c"
解决方案 There are a couple of ways to do this, but you need to use some macros to either define or adapt the struct.
You can use the REFLECTABLE
macro given in this answer to define the struct like this:
struct A
{
REFLECTABLE
(
(int) a,
(int) b,
(int) c
)
};
And then you can iterate over the fields and print each value like this:
struct print_visitor
{
template<class FieldData>
void operator()(FieldData f)
{
std::cout << f.name() << "=" << f.get() << std::endl;
}
};
template<class T>
void print_fields(T & x)
{
visit_each(x, print_visitor());
}
A x;
print_fields(x);
Another way is to adapt the struct as a fusion sequence (see the documentation). Here's an example:
struct A
{
int a;
int b;
int c;
};
BOOST_FUSION_ADAPT_STRUCT
(
A,
(int, a)
(int, b)
(int, c)
)
Then you can print the fields as well using this:
struct print_visitor
{
template<class Index, class C>
void operator()(Index, C & c)
{
std::cout << boost::fusion::extension::struct_member_name<C, Index::value>::call()
<< "="
<< boost:::fusion::at<Index>(c)
<< std::endl;
}
};
template<class C>
void print_fields(C & c)
{
typedef boost::mpl::range_c<int,0, boost::fusion::result_of::size<C>::type::value> range;
boost::mpl::for_each<range>(boost::bind<void>(print_visitor(), boost::ref(c), _1));
}
这篇关于迭代通过Struct和类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!