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

后端 未结 13 995
轻奢々
轻奢々 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:16

    Well, not directly. But you can achieve that by using an additional temporary "index" array of pointers of pointer-to-member type.

    For example

    rect a_rect[100];
    int factor;
    ...
    // We need to multiply all members of all elements of `a_rect` array by `factor`
    
    // Prepare index array
    int rect::*rect_members[4] = { &rect::x, &rect::y, &rect::width, &rect::height };
    
    // And multiply
    for (i = 0; i < 100; ++i)
      for (j = 0; j < 4; ++j)
        a_rect[i].*rect_members[j] *= factor;
    

    Of course, if you need to do it often, you can use a permanent index array rect_members initialized at the program startup.

    Note that this method does not employ any hacks, as some other methods do. Pointers of pointer-to-member type are rarely used, but this is actually one of the things they were introduced for.

    Again, if you need to do it often, the proper thing to do would be to make the pointer array a static const member of the struct

    struct rect
    {
      int x;
      int y;
      int width;
      int height;
    
      static int rect::* const members[4];
    };
    
    int rect::* const rect::members[4] = { &rect::x, &rect::y, &rect::width, &rect::height };
    

    and when you need to iterate over these members, you'd just access struct elements as s.*rect::members[i].

提交回复
热议问题