我创建了一个地图作为解决方案的一部分
enum Opcode {
OpFoo,
OpBar,
OpQux,
};
// this should be a pure virtual ("abstract") base class
class Operation {
// ...
};
class OperationFoo: public Operation {
// this should be a non-abstract derived class
};
class OperationBar: public Operation {
// this should be a non-abstract derived class too
};
std::unordered_map<Opcode, std::function<Operation *()>> factory {
{ OpFoo, []() { return new OperationFoo; } }
{ OpBar, []() { return new OperationBar; } }
{ OpQux, []() { return new OperationQux; } }
};
Opcode opc = ... // whatever
Operation *objectOfDynamicClass = factory[opc]();
但遗憾的是我的编译器gcc-4.4.2不支持lambda函数。
我想使用boost库(lambda / phoenix)
进行替代(可读)实现有没有办法偷偷用C ++ std :; lambdas和std :: functions进入我的编译器-std = C ++ 0x,像这样的选项都失败...... :(
PS:请提供可读的解决方案
答案 0 :(得分:1)
您可以使用Phoenix new_
:
std::unordered_map<Opcode, std::function<Operation*()>> factory {
{ OpFoo, boost::phoenix::new_<OperationFoo>() },
{ OpBar, boost::phoenix::new_<OperationBar>() },
//{ OpQux, []() { return new OperationQux; } },
};
<强> Live On Coliru 强>
#include <boost/phoenix.hpp>
#include <unordered_map>
#include <functional>
enum Opcode {
OpFoo,
OpBar,
OpQux,
};
namespace std
{
template<> struct hash<Opcode> : std::hash<int>{};
}
// this should be a pure virtual ("abstract") base class
class Operation {
// ...
};
class OperationFoo: public Operation {
// this should be a non-abstract derived class
};
class OperationBar: public Operation {
// this should be a non-abstract derived class too
};
std::unordered_map<Opcode, std::function<Operation*()>> factory {
{ OpFoo, boost::phoenix::new_<OperationFoo>() },
{ OpBar, boost::phoenix::new_<OperationBar>() },
//{ OpQux, []() { return new OperationQux; } },
};
int main() {
Opcode opc = OpFoo;
Operation *objectOfDynamicClass = factory[opc]();
delete objectOfDynamicClass;
}