views:

1029

answers:

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?

+2  A: 

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

Keith Nicholas
+6  A: 

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
A: 

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

Keith Nicholas
You can edit your own original answer - just click the "edit" link
1800 INFORMATION
excellent, thats a lot cooler :)
Keith Nicholas
+1  A: 

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
This is a reasonable option, but you should go into more detail
1800 INFORMATION
Thanks 1800. I should have probably added an example to make it clear why boost any would be good. So now I did.
Robert Gould