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

Solution 1:

Not really. Programatically obtaining a list of the elements of a struct requires reflection, which C++ does not support.

Your two options are to just give the struct a method that does this the long-winded way and then use that method in all other places, or to manually mimic reflection, for example by giving the struct another element which is an array of pointers to all of its other elements (built within the struct's constructor), and then looping over that to perform the scaling function.

Solution 2:

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)