0

I was trying to create a lambda function inside a c++ class, but it is giving compilation error. Code looks like:

class Test {

  public:
    struct V {
            int a;
    };

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

};

The compilation error I am getting is:

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

Any explanation?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
saha
  • 97
  • 8

1 Answers1

2

You cannot construct a class member using () inside the class body. The compiler interprets this as trying to make a function. Since you have C++11 you can use brace initialization to overcome this like

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

};
NathanOliver
  • 171,901
  • 28
  • 288
  • 402