-1

If I have created a class like this:

struct test{
  int a;
  int b;
  string c;
};

and wanted to iterate through each data member as if it was an array how could i do it?(Assuming the number of members may change in a future update.)

k.S
  • 89
  • 9
  • 1
    https://github.com/apolukhin/magic_get – HolyBlackCat Dec 15 '18 at 16:35
  • Would be straight-forward if you could hold the data members in a tuple. – uv_ Dec 15 '18 at 16:37
  • If all members data types is the same you can just cast pointer to your stuct to pointer to members type. But it is trick. – Dmytro Dadyka Dec 15 '18 at 16:37
  • 1
    *Why* do you want that? What is the *actual* problem that makes you need something like that? Perhaps a `struct` isn't the correct data structure for your design? Perhaps even the design is flawed? Oh and please read [about the XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem since you're question is an example of one. – Some programmer dude Dec 15 '18 at 16:38
  • @DmytroDadyka Iterating the data members directly technically has undefined behaviour. – George Dec 15 '18 at 16:41
  • It's not a specific problem I was just wondering if something like this could be done since i learned a similar thing could be done if all data members were the same type. – k.S Dec 15 '18 at 16:41

1 Answers1

-1

Immediately, I note that C ++ does not support arrays of elements of different types, so there is no solution in your case. But with identical members you can create an array of pointers to members and use it in the loop:

struct test {
   int a0 = 0;
   int a1 = 1;
   int a2 = 2;
   int a3 = 3;
   virtual ~test() {};
};

int main()
{
   test t;
   int* ptr[4] = { &t.a0, &t.a1, &t.a2, &t.a3 };
   for (int i = 0; i < sizeof(ptr) / sizeof(int*); i++)
      std::cout << *ptr[i] << std::endl;

   return 0;
}
Dmytro Dadyka
  • 2,208
  • 5
  • 18
  • 31