2014-11-04 5 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 람다 기능을 지원하지 않습니다의 일환으로 만든지도가 있습니다.

내가

는 C에서 ++ 표준을 스 네크 어떤 방법이 있나요이 사용 부스트 라이브러리 (읽기) 구현 (람다/피닉스) 대체하고 싶습니다

:;. 내 컴파일러 -std에 람다 및 표준 : : 기능

답변

1

당신은 피닉스 new_을 사용할 수 있습니다 읽을 수있는 솔루션을 제공하십시오 : = C + +0, 이와 같은 옵션 :(이

PS ... 실패

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; 
}