遍历结构和类成员

时间:2023-01-22
本文介绍了遍历结构和类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

是否可以在 C++ 中遍历 Struct 或 Class 以找到其所有成员?例如,如果我有 struct a 和 class b:

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;
}

是否可以循环它们说得到一个打印语句,说结构 a 具有名为 a、b、c 的 int"或b 类具有名为 a、b、c 的 int"

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.

您可以使用 this answer 中给出的 REFLECTABLE 宏来定义这样的结构:

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));
}

这篇关于遍历结构和类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:模板:父类成员变量在继承类中不可见 下一篇:你如何在 C++ 中创建一个静态类?

相关文章

最新文章