您可以实现工厂:从操作码(作为整数/枚举),类名(作为字符串)等映射到动态实例化类的函数:
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]();
Run Code Online (Sandbox Code Playgroud)
作为奖励,您可以(并且可能应该)在工厂lambda函数的返回类型和使用抽象类操作的其他位置使用智能指针(std::unique_ptr或std::shared_ptr)而不是原始指针.
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |