【问题标题】:Defining a lambda function in C++11 doesn't compile inside class在 C++11 中定义 lambda 函数不会在类内部编译
【发布时间】:2018-07-13 14:03:05
【问题描述】:

我试图在 c++ 类中创建一个 lambda 函数,但它给出了编译错误。代码如下:

class Test {

  public:
    struct V {
            int a;
    };

    priority_queue<V, vector<V>, function<bool(V&, V&)>>
            max_heap([](V& a, V& b) { return true; } );

};

我得到的编译错误是:

test.cpp:32:22: error: expected identifier before '[' token
             max_heap([](V& a, V& b) { return true; } );
                      ^
test.cpp:32:35: error: creating array of functions
             max_heap([](V& a, V& b) { return true; } );
                                   ^
test.cpp:32:37: error: expected ')' before '{' token
             max_heap([](V& a, V& b) { return true; } );
                                     ^
test.cpp:32:54: error: expected unqualified-id before ')' token
             max_heap([](V& a, V& b) { return true; } );

有什么解释吗?

【问题讨论】:

    标签: c++ c++11 lambda most-vexing-parse


    【解决方案1】:

    您不能在类体内使用() 构造类成员。编译器将此解释为试图创建一个函数。由于您拥有 C++11,因此您可以使用大括号初始化来克服这种情况

    class Test {
    
      public:
        struct V {
                int a;
        };
    
        std::priority_queue<V, vector<V>, function<bool(V&, V&)>>
                max_heap{[](V& a, V& b) { return true; } };
    
    };
    

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2014-10-07
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多