Iterating over a struct in C++

前端 未结 8 724
说谎
说谎 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:44

    can I iterate over the members of a struct in standard c++?

    No, standard c++ doesn't provide a method for accomplishing what you are asking for, you "iterate" elements of a container - you cannot iterate over members of a certain type.

    "reflection" (as this type of feature is most often referred to isn't part of C++).


    in c++11 you could use a std::tuple instead of your struct A, it will store the same kind of elements and is far easier to iterate over (using some template magic).

    the elements won't have names ranging from 'a' to 'c' but if you'd like to print it that way this of course can be accomplished by some extra lines of code.

    To access a specific element you'll use std::get (your_tuple) where N is a integral ranging from 0 to std::tuple_size>::value - 1 (ie. 2).


提交回复
热议问题