0

I want to modify a specific object member of an array of objects. So I intend to pass the object member to a method that would iterate through the array and modify the specified member for each object:

Object *objs[10];
if (condition)
   modify_all(objs, Object.x, set_value);

But I can't pass Object.x like that. Is there a better way of doing this? I need something like this, since modfiy_all doesn't know which member to modify.

EDIT: I'm just trying to refactor repetitive iterations of the array.

lamino
  • 132
  • 1
  • 9
  • you might be able to use templates to do this, see for example [this question](http://stackoverflow.com/q/672843/33499) – wimh Oct 11 '14 at 21:00
  • That sounds a bit complicated but I'm going to give it a try. Thanks! – lamino Oct 11 '14 at 21:10
  • yes, it is complicated, but what you are trying to do is a bit strange. It is probably easier not to use a function at all and just juse a for loop. If you use c++11, you can use a callback with lambda function as an alternative. – wimh Oct 11 '14 at 21:21

1 Answers1

0

You can pass a char or an int instead of the object member, and that string or int will specify which member should be modified. For example:

Object *objs[10];
if (condition)
   modify_all(objs, "x", set_value);

or

Object *objs[10];
if (condition)
   modify_all(objs, 0, set_value);

Inside modify_all you can use a switch statement based on this parameter sent.

Laura Maftei
  • 1,863
  • 1
  • 15
  • 25