Boost lambda example

放肆的年华 提交于 2019-12-24 03:35:16

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/26730365/boost-lambda-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!