Is there a way of applying a function to each member of a struct in c++?

后端 未结 13 1098
轻奢々
轻奢々 2021-01-13 02:31

You have a simple struct, say:

typedef struct rect
{
    int x;
    int y;
    int width;
    int height;
}
rect;

And you want to multiply

13条回答
  •  情歌与酒
    2021-01-13 03:15

    If all are the same type, use a union combined with an anonymous struct, inside of your struct:

    struct MyStruct {
      union {
        int data[4];
        struct {
          int x,y,z,w;
        }
      };
    };
    

    then:

    MyStruct my_struct;
    cout << my_struct.x << my_struct.y << my_struct.z << my_struct.w;
    for (size_t i = 0; i < 4; ++i)
      some_function(my_struct.data[i]); // access the data via "data" member
    cout << my_struct.x << my_struct.y << my_struct.z << my_struct.w; // voila!, stryct data has changed!
    

    If youre using different types have a look at boost::fusion

提交回复
热议问题