tags:

views:

370

answers:

14

You have a simple struct, say:

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

And you want to multiply each element by a factor. Is there a more concise way of performing this operation, other than multiplying each member by the value?

A: 

if all your elements are of the same type:

for (int i = 0; i < sizeof(rect) / sizeof(rect.x) ; ++i) {
    do_something(reinterpret_cast<int *>(adress_of_your_struct) + i);
}

with do_something expecting a pointer to int

Benoit
This isn't portable because it assumes that there is no padding between the elements of the structure, which is not guaranteed.
Tyler McHenry
code brevity at the cost of type safety. still, very concise. +1
Andrew Garrison
@Andrew: Type safety should _never_ be sacrificed for the sake of brevity.
James McNellis
@James: What about when you have 6 minutes to solve a programming puzzle at an ACM programming competition?
Andrew Garrison
@Andrew: I can start prefixing my commentary with "when writing real-world software that has real-world requirements," if you think that would be clearer.
James McNellis
@James: LOL, touche.
Andrew Garrison
+10  A: 

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.

Tyler McHenry
What about unions? In particular, Microsoft's usage of them in D3DXMATRIX and D3DXVECTOR.
Andrew Garrison
That's really the same thing as the casting solution that others have posted, but with a nicer syntax. It is similarly reliant on the behavior of a particular compiler and standard C++ doesn't guarantee that it will work.
Tyler McHenry
Not an exhaustive list of options. You can use pointers of **pointer-to-member** type, as suggested in my answer. This is similar to your second option, but in that case you wouldn't have to create a separate pointer array for each struct instance. Instead you use a single array that is applicable to all instances (you can make it *static* member of the struct if you want). In fact, *this* is the correct way to "manually mimic reflection", not what you suggest above.
AndreyT
+10  A: 

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)

James McNellis
Some suggestions, although outside the scope of the original question: (i) Use a symbolic constant instead of `4`. (ii) Accept the multiplier (`2` in the example) as an input argument.
ArunSaha
A: 

horrific hack

int *arr = (int*)&my_rect;
for (int i = 0; i < sizeof(rect)/sizeof(int); i++)
{
     arr[i] *= factor;
}
pm100
This isn't portable because it assumes that there is no padding between the elements of the structure, which is not guaranteed.
Tyler McHenry
well duh, hence 'horrible hack'. It will work on most 32 bits machines tho
pm100
+5  A: 

If all the values fit into a 128-bit vector, then you could use SIMD instructions to multiply them all at once. For example Intel's Integrated Performance Primitives (IPP) has primitives for addition, subtraction, multiplication etc. on vectors.

It's probably overkill unless you are doing a lot of compute intensive operations.

locka
A: 

A solution via a new class:

  • Create a class with a template<class T> class Array generic array, (see how),
  • Fill the array with your properties, one property as an element of the array.
  • Ensure all types can be multiplied by a numeric value (or overload the * operator for a type if necessary / create a specific method for that object)
  • Create a method multiply that performs a loop on the array and multiplies each element by a given value.
ring0
A: 

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;
    }
}
Andrew Garrison
+2  A: 

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

Viktor Sehr
this is ugly and horrible, but it probably the best way of doing exactly what the OP asked for... +1
rmeador
+7  A: 

Boost.Fusion offers the BOOST_FUSION_ADAPT_STRUCT macro, which can turn any struct into a Fusion sequence, which Fusion can then iterate over (as demoed in the Quick Start).

Another option is to use a third-party C++ reflection library like Reflex to iterate over a struct's members.

However, all of this may be overkill for your purposes; manually listing each of the class's members may be less elegant, but it's much simpler, and simplicity in coding is important.

Josh Kelley
Beat me to it by 5 minutes...
Eugen Constantin Dinca
+1 for `BOOST_FUSION_ADAPT_STRUCT`: the quickest way to get compile-time reflexion.
Matthieu M.
+3  A: 

Like everyone has said, you can't do it directly, but there's nothing stopping you from overloading the * operator:

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

rect operator*(const rect& r, int f)
{
  rect ret=r;
  ret.x*=f;
  ret.y*=f;
  ret.width*=f;
  ret.height*=f;
  return ret;
}

then you can do this

rect r;
//assign fields here
r=r*5;
miked
This is is only clean solution so far... I had to remove my answer, you were faster
paul_71
+2  A: 

Assuming you are using a C++ compiler (not C), make it a class and create a member function to do this. I am suprised at all the awkward solutions presented to a simple problem. What does a reflective solution buy you? Are you continually adding new members to this class, so you want to save yourself the step of modifying the member function in the future? If that is a seriously a potential time-saver, it smells of a class doing too much.

It is inevitable there will be repeated functionality acting on the members of a structure, so why not make it a class from the start?

actom
+1  A: 

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].

AndreyT
A: 
andand
A: 

a related posted answer

nbourbaki