4

After having implemented the strategy pattern, I wanted to make an array of the interface-type, to which I can then add any concrete type.

For those who don't know the strategy pattern: http://en.wikipedia.org/wiki/Strategy_pattern In this particular example I would want to make a StrategyInterface array, which I can then fill with concrete type's A, B and C. However, because this is an abstract class, I can't get it done. Is there a way to do this, or is it completely impossible, without removing the abstract method?

James Curran
  • 101,701
  • 37
  • 181
  • 258
user23163
  • 515
  • 2
  • 9
  • 15
  • Even if you could make an array/vector of the interface then you would suffer the problem of Object slicing. So another reason to use pointers. – Martin York Oct 05 '08 at 21:15

4 Answers4

7

Make the array store pointers to the interface type:

typedef std::vector<Interface *> Array;
Array myArray;
myArray.push_back(new A());

Additionally, you can use ptr_vector which manages memory for you:

typedef boost::ptr_vector<Interface> Array;
// the rest is the same
1800 INFORMATION
  • 131,367
  • 29
  • 160
  • 239
2

store pointers not objects..... use boost::shared_ptr if you are wanting to store objects.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

errr, for example... std::vector< boost::shared_ptr< AbstractStrategy > >

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

How about using boost any?

Here's an example of what it would look like

#include <list>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::list<boost::any> many;

void append_int(many & values, int value)
{
   boost::any to_append = value;
   values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
   values.push_back(value);
}

void append_char_ptr(many & values, const char * value)
{
   values.push_back(value);
}

void append_any(many & values, const boost::any & value)
{
   values.push_back(value);
}

void append_nothing(many & values)
{
   values.push_back(boost::any());
}

Seems nice and elegant, plus you get well tested code and can treat your values as objects instead of pointers

Note: These function names are informative, but you could use overriding to have a single interface.

Robert Gould
  • 68,773
  • 61
  • 187
  • 272