在实现策略模式之后,我想创建一个interface-type数组,然后我可以添加任何具体类型。
对于那些不了解策略模式的人: http://en.wikipedia.org/wiki/Strategy_pattern 在这个特定的例子中,我想创建一个StrategyInterface数组,然后我可以填充具体类型的A,B和C.但是,因为这是一个抽象类,我无法完成它。如果没有删除抽象方法,有没有办法做到这一点,还是完全不可能?
答案 0 :(得分:6)
使数组存储指向接口类型的指针:
typedef std::vector<Interface *> Array;
Array myArray;
myArray.push_back(new A());
此外,您可以使用ptr_vector为您管理内存:
typedef boost::ptr_vector<Interface> Array;
// the rest is the same
答案 1 :(得分:2)
存储指针而非对象.....如果您想存储对象,请使用boost :: shared_ptr。
答案 2 :(得分:1)
错误,例如...... 的std ::矢量&lt;升压:: shared_ptr的&LT; AbstractStrategy&gt; &GT;
答案 3 :(得分:1)
如何使用boost any?
以下是
的示例#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());
}
看起来漂亮而优雅,加上你得到了经过良好测试的代码,可以将你的值视为对象而不是指针
注意:这些函数名称是提供信息的,但您可以使用覆盖来创建单个接口。