【问题标题】:Boost lambda example提升 lambda 示例
【发布时间】:2014-11-04 08:10:16
【问题描述】:

我有一个作为解决方案的一部分创建的地图

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 函数。

我想要一个使用 boost 库的替代(可读)实现。(lambda / phoenix)

有什么办法可以将 C++ std:;lambdas 和 std::functions 偷偷溜进我的编译器 -std=C++0x,像这样的选项都失败了...:(

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

【问题讨论】:

    标签: c++ boost boost-lambda


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多