c++boostboost-lambda

Boost lambda example


I have a map created as a part of solution

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]();

But unfortunately my compiler gcc-4.4.2 does not support lambda functions.

I would like an alternate (readable ) implementation for this using boost library.(lambda / phoenix )

Is there any way to sneek in C++ std:;lambdas and std::functions into my compiler -std=C++0x, options like these are failing...:(

PS : Please provide a readable solution


Solution

  • You can use 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;
    }