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

后端 未结 13 1124
轻奢々
轻奢々 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 02:57

    If you can re-arrange your struct to take be a union instead, you can do something similar to what Microsoft has done with DirectX.

    union Rect
    {
        struct
        {
            int x;
            int y;
            int width;
            int height;
        };
    
        int members[4];
    };
    
    void multiply(Rect& rect, int factor)
    {
        for(int i = 0; i < 4; i++)
        {
            rect.members[i] *= factor;
        }
    }
    

提交回复
热议问题