Iterating over a struct in C++

前端 未结 8 732
说谎
说谎 2020-11-28 07:08

I have a structure

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;

I want to iterate over each an every member of the structure

8条回答
  •  暖寄归人
    2020-11-28 07:22

    Perhaps you can string something together using Boost Fusion/Phoenix:

    See it live on Coliru!

    #include 
    #include 
    #include 
    using boost::phoenix::arg_names::arg1;
    
    #include 
    #include 
    
    struct A
    {
        int a;
        int b;
        std::string c;
    };
    
    BOOST_FUSION_ADAPT_STRUCT(A, (int,a)(int,b)(std::string,c));
    
    int main()
    {
        const A obj = { 1, 42, "The Answer To LtUaE" };
    
        boost::fusion::for_each(obj, std::cout << arg1 << "\n");
    }
    

    Update: Recent versions of boost can use C++11 type deduction:

    BOOST_FUSION_ADAPT_STRUCT(A,a,b,c);
    

    Output:

    1
    42
    The Answer To LtUaE
    

提交回复
热议问题