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

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

    No; there is no way to iterate over the members of a struct.

    In this particular case, though, you can accomplish your goal by using an array:

    struct rect
    {
        // actually store the data in an array, not as distinct elements
        int values_[4];
    
        // use accessor/mutator functions to modify the values; it is often best to
        // provide const-qualified overloads as well.
        int& x()      { return values_[0]; }
        int& y()      { return values_[1]; }
        int& width()  { return values_[2]; }
        int& height() { return values_[3]; }
    
        void multiply_all_by_two()
        {
            for (int i = 0; i < sizeof(values_) / sizeof(values_[0]); ++i)
                values_[i] *= 2;
        }
    };
    

    (note that this example doesn't make much sense (why would you multiply x, y, height and width by two?) but it demonstrates a different way to solve this sort of problem)

提交回复
热议问题