Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lambda as STL Compare method in a template class?

I'm trying to implement a priority_queue which holds A<T> objects and use a custom Compare method/type. According to the reference example, this is my code:

template <class T>
class A{
    T value;
    A(T _value):value(_value){}
};

template <class T>
class ProblematicClass{

    auto cmp = [](A<T>* l, A<T>* r) {return l->value > r->value; };

    std::priority_queue < A<T>*, std::vector<A<T>*>, decltype(cmp) > q(cmp);
};

But I'm getting the following error:

error C2853: 'cmp' : a non-static data member cannot have a type that contains 'auto'

I tried to make lamda definition static, but it results in a new syntax error:

error C2143: syntax error : missing '}' before 'return'

Can you please help me with it?

UPDATE: I'm using VS2013

like image 863
Emadpres Avatar asked Jul 12 '26 17:07

Emadpres


1 Answers

Its not necessary to make cmp static. Instead, you can do this:

template <class T>
class A{
    T value;
    A(T _value):value(_value){}
};

template <class T>
class ProblematicClass{

    std::function<bool(A<T>*, A<T>*)> cmp = [](A<T>* l, A<T>* r) {return l->value > r->value; };

    std::priority_queue < A<T>*, std::vector<T>, decltype(cmp) > q;
};

Don't forget to include <functional> for this to work.

like image 66
Kunal Puri Avatar answered Jul 15 '26 07:07

Kunal Puri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!