C++策略设计模式,制作一个接口数组
C++ Strategy Design Pattern, making an interface array
实现策略模式后,我想制作一个接口类型的数组,然后可以向其中添加任何具体类型。
对于那些不知道战略模式的人:http://en.wikipedia.org/wiki/Strategy_pattern在这个特定的例子中,我想制作一个StrategyInterface数组,然后我可以用具体类型的a、B和C填充它。但是,因为这是一个抽象类,我无法完成它。有没有一种方法可以做到这一点,或者如果不删除抽象方法,这是完全不可能的?
使数组存储指向接口类型的指针:
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
存储指针而不是对象。。。。。如果要存储对象,请使用boost::sharedptr。
errr,例如。。。std::vector<boost::shared_ptr<抽象策略>>
使用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());
}
看起来很好,很优雅,加上你得到了经过良好测试的代码,可以将你的值视为对象,而不是指针
注意:这些函数名称提供了信息,但您可以使用重写来拥有单个接口。
相关文章:
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 我可以在具有一个标头和一个接口的 cpp 文件中有多个嵌入吗?
- 一个C头文件可以被认为是一个接口吗
- WINUSB_ControlTransfer只能在设备上可用的两个接口中的一个上使用,而不能在另一个接口上使用
- 如何制作一个满足SWIG中接口的python类
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- 2 个 COM 对象,并在另一个对象中使用其中一个对象的接口
- 尝试向 COM 对象添加另一个接口时出现静态强制转换错误 C2440
- BASIC_SOCKETD_ACCEPTOR接口在Boost 1.66中更改.这是一个错误
- 继承了另一个接口的接口的实现
- 在c++中的另一个相同类型的接口中克隆一个接口
- 在C++中,我可以像在Java中一样拥有一个接口变量吗
- 用C++实现一个接口
- 如何为一个简单的转换例程设计一个接口
- 如何用c++逻辑在c#或VB中创建一个接口
- 在两个不同的类中实现一个接口
- c++中的接口:为什么我需要一个接口类+另一个父类
- 用C++实现一个接口
- 声明一个接口,其方法具有实现该接口的类的参数
- C++策略设计模式,制作一个接口数组