作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
是否可以在 C++ 中遍历 Struct 或 Class 以查找其所有成员?例如,如果我有 struct a 和 class b:
struct a
{
int a;
int b;
int c;
}
class b
{
public:
int a;
int b;
private:
int c;
}
是否可以循环它们以获取打印语句,说“结构 a 具有名为 a、b、c 的整数”或“b 类具有名为 a、b、c 的整数”
最佳答案
有几种方法可以做到这一点,但您需要使用一些宏来定义或调整结构。
您可以使用 this answer 中给出的 REFLECTABLE
宏像这样定义结构:
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);
另一种方法是将结构调整为融合序列(参见 the documentation)。这是一个例子:
struct A
{
int a;
int b;
int c;
};
BOOST_FUSION_ADAPT_STRUCT
(
A,
(int, a)
(int, b)
(int, c)
)
然后您也可以使用以下方法打印字段:
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));
}
关于c++ - 遍历结构和类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19059157/
我是一名优秀的程序员,十分优秀!