2014-11-04 88 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; 
}