Home > Net >  C 11: how to use lambda as type parameter, where it requires a "functor type" like std::l
C 11: how to use lambda as type parameter, where it requires a "functor type" like std::l

Time:06-19

I'm trying to pass a type parameter to priority_queue, just like std::less or std::greater, like this:

priority_queue<int, vector<int>, [](int x, int y){return x>y;})> q;

It doesn't compile, then I added decltype, still fails:

priority_queue<int, vector<int>, decltype([](int x, int y){return x>y;}))> q;

Question is, can we use lambda in this case, how to achieve it?

CodePudding user response:

There are multiple ways:

  1. Let the compile deduce the type of lamabda by using decltype(). But one thing you need to keep in mind: Prior to C 20, lambda type does not have a default constructor. As of C 20, stateless lambda (lambda without captures) has a default constructor, but stateful lambda (i.e., lambda with captures) has no default constructor (This is documented on cppreference.om). Why does a default constructor matter here? The answer is if a default constructor exists, here in your example of priority_queue, you don't have to pass a cmp argument to the constructor once you specified the lambda type. Since the default constructor exists only for stateless lambda since C 20, you'd better explicitly pass a cmp argument to the constructor:
auto cmp = [](int x, int y){return x>y;}; 
priority_queue<int, vector<int>, decltype(cmp)> q(cmp);
  1. Use the <functional> header to explicitly specify the lambda type:
#include <functional>
...
priority_queue<int, vector<int>, function<bool(int, int)>> q(cmp);
  1. Use a function-obejct class. In this case, you only need to specify the function-object class a a template type argument, and you don't need to pass the cmp argument to the constructor, because your own defined function-object class has a default (synthesized) constructor.
struct Cmp {
    bool operator()(int x, int y) {return x > y;}
};
priority_queue<int, vector<int>, Cmp> q;
  1. Use the library-defined function objects whenever possible.
priority_queue<int, vector<int>, std::greater<int>> q;

CodePudding user response:

I removed the last ')' from

decltype([](int x, int y){return x>y;}))

decltype([](int x, int y){return x>y;})

and it compiled succesfully.

  • Related