Varg Nord
Varg Nord

Reputation: 33

What is the difference when passing function's reference and lambda expression as arguments?

I am using custom comparators to priority_queue, finding different behaviors. I already knew that stl containers need specific type passing to template declaration. When using normal functions, it should be:

bool cmp(pair<int, int> &lhs, pair<int, int> &rhs) {
    return lhs.first > rhs.first;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> pq1(v.begin(), v.end(), cmp);

But when using lambda, I find the correct way is:

auto comp = [](const pair<int, int>& lhs, const pair<int, int>& rhs){return lhs.second < rhs.second;};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq2(v.begin(), v.end(), comp);

I referred to decltype but did not come out an opinion. Could someone explain how compiler treats decltype(&function) and decltype(lambda)?

Upvotes: 1

Views: 55

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

That's because lambda expressions create an object (of an anonymous class).

If you use &comp then you get a pointer to the object, which is not callable.


The lambda you have is basically equivalent to

struct
{
    bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs)
    {
        return lhs.second < rhs.second;
    }
} comp;

Upvotes: 2

Related Questions