"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to iterate through struct and class members in C++?

How to iterate through struct and class members in C++?

Published on 2024-11-02
Browse:766

 How to iterate through struct and class members in C  ?

Iterating Through Struct and Class Members

C provides various mechanisms to iterate through the members of structs and classes. To achieve this, you can employ several techniques.

Defining the Struct with a Macro:

One approach is to use the REFLECTABLE macro, as seen in the following example:

struct A
{
    REFLECTABLE
    (
        (int) a,
        (int) b,
        (int) c
    )
};

By using this macro, you can conveniently iterate over the fields and print their values as follows:

struct print_visitor
{
    template
    void operator()(FieldData f)
    {
        std::cout 
void print_fields(T & x)
{
    visit_each(x, print_visitor());
}

A x;
print_fields(x);

Adapting the Struct as a Fusion Sequence:

Another option is to adapt the struct as a Boost.Fusion sequence. Consider the following example:

struct A
{
    int a;
    int b;
    int c;
};

BOOST_FUSION_ADAPT_STRUCT
(
    A,
    (int, a)
    (int, b)
    (int, c)
)

With this adaptation, you can iterate over the fields using the following code:

struct print_visitor
{
    template
    void operator()(Index, C & c)
    {

        std::cout ::call() 
                  (c) 
                  
void print_fields(C & c)
{
    typedef boost::mpl::range_c::type::value> range;
    boost::mpl::for_each(boost::bind(print_visitor(), boost::ref(c), _1));
}

These techniques allow you to effectively iterate through struct and class members in C .

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3