2014-11-04 121 views
2

我有作为的解决方案升压拉姆达例如

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函数的一部分创建的地图。

我想替代(可读)实现此使用升压库(拉姆达/凤)

是否有任何方式在C++斯内克STD:; lambda表达式和std ::功能于我的编译器-std = C++ 0x中,像这些选项都没有... :(

PS:请提供一个可读的解决方案

回答

1

您可以使用凤凰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; 
}