C ++ Strategy Design Pattern creating an interface array

After implementing the strategy template, I wanted to create an array of an interface type to which I can add any specific type.

For those who do not know the strategy template: http://en.wikipedia.org/wiki/Strategy_pattern In this specific example, I would like to create an array of StrategyInterface, which I can then fill with specific types A, B and C. However, since this is abstract class, I can not do this. Is there a way to do this, or is it impossible, without removing the abstract method?

+4
source share
4 answers

Make array storage pointers to interface type:

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

Alternatively, you can use ptr_vector, which manages the memory for you:

 typedef boost::ptr_vector<Interface> Array; // the rest is the same 
+6
source

store pointers, not objects ..... use boost :: shared_ptr if you want to store objects.

+2
source

errr, for example ... std :: vector <promotion :: shared_ptr <AbstractStrategy →

+1
source

How about using boost any?

Here is an example of how it will look

 #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()); } 

It 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 can use redefinition to have one interface.

+1
source

Source: https://habr.com/ru/post/1277485/


All Articles