0
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <queue>

auto cmp = [](int a, int b) {
    return a > b;
};

class Test {
private:
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
};

int main(int argc, char const *argv[])
{   
    Test test;
    return 0;
}

The output is below: enter image description here

However, when I use the priority_queue in the main function, it can use the cmp.

Moreover, when I delete the 'cmp' in the 'pq'

auto cmp = [](int a, int b) {
    return a > b;
};

class Test {
private:
std::priority_queue<int, std::vector<int>, decltype(cmp)> pq;
};

int main(int argc, char const *argv[])
{   
    Test test;
    return 0;
}

the complier told me:

enter image description here

#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <queue>

auto cmp = [](int a, int b) {
    return a > b;
};

int main(int argc, char const *argv[])
{   

    std::priority_queue<int, std::vector<int>, decltype(cmp)> pq(cmp);
    pq.push(1);
    std::cout << pq.top() << std::endl;
    return 0;
}

I do not know why? I know lambda is a anonymous class, but why in a class it cannot use, in the main function it can use?

Ustinian
  • 39
  • 6
  • Note that with C++20 or higher, you do not need to repeat `cmp`. Having `decltype(cmp)` as the third template parameter is enough. – kotatsuyaki Dec 23 '22 at 14:30
  • I delete the `cmp` in the 'pq`, the complier told me I use delete function – Ustinian Dec 23 '22 at 14:39
  • 2
    See dupe: [Why can't member initializers use parentheses?](https://stackoverflow.com/questions/24836526/why-cant-member-initializers-use-parentheses) – Jason Dec 23 '22 at 14:39
  • 1
    The form `type name(arguments)` in a class definition is a member function declaration. – molbdnilo Dec 23 '22 at 14:41
  • You need to enable C++20 or higher so that closure types have default constructors. See the `ClosureType::ClosureType()` section in [Lambda expressions on cppreference](https://en.cppreference.com/w/cpp/language/lambda). – kotatsuyaki Dec 23 '22 at 14:42

1 Answers1

3

Welcome to the wonderful world of the Most Vexing Parse (well, not really, but close enough).

class Test {
private:
    std::priority_queue<int, std::vector<int>, decltype(cmp)> pq{cmp};
};

gcc 12 compiles this without any errors. Always use the uniform initialization syntax. It's your friend.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148