"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 can I iterate over struct and class members in C++ to access their names and values at runtime?

How can I iterate over struct and class members in C++ to access their names and values at runtime?

Published on 2024-11-06
Browse:966

How can I iterate over struct and class members in C   to access their names and values at runtime?

Iterating Over Struct and Class Members

In C , it is possible to iterate through the members of a struct or class to retrieve their names and values. Here are a few approaches to achieve this:

Using Macros

The REFLECTABLE macro can be used to define structs that allow for introspection. The macro defines the members of the struct as a comma-separated list of type-name pairs. For example:

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

Once the struct is defined, you can use a visitor function to iterate over its members and print their names and values:

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 Structs as Fusion Sequences

Another approach is to adapt the struct as a fusion sequence using the BOOST_FUSION_ADAPT_STRUCT macro. This macro defines the struct members as a sequence of elements with the corresponding type and value. For example:

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

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

Once the struct is adapted, you can use a range loop to iterate over the members and print their names and values:

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

Both these approaches allow you to introspect structs and classes, providing access to their members and their values at runtime.

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