3

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Emadpres
  • 3,466
  • 2
  • 29
  • 44
  • You need to be more descriptive than "it doesn't work", because the number of ways that it might not work is uncountable. Besides, [it appears to work](https://godbolt.org/z/2GCAuI) on at least GCC 8.2. – zneak Feb 06 '19 at 00:25

2 Answers2

2

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.

Kunal Puri
  • 3,419
  • 1
  • 10
  • 22
  • Thanks. It's working. One follow-up question: Isn't it possible/better to somehow define `cmp` as *static* since it's a shared entity for the class? (btw, simply adding `static` keyword produce syntax errors) – Emadpres Feb 06 '19 at 00:40
  • 2
    It is possible. using `static auto cmp` works even with GCC 4.9.2. Not sure about VS 2013. According to me, it should be `static`. – Kunal Puri Feb 06 '19 at 00:42
2

For me static works perfectly

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

For non static... what about passing through a using?

using lType = decltype([](A<T>* l, A<T>* r) {return l->value > r->value; });

lType cmp = lType{};
max66
  • 65,235
  • 10
  • 71
  • 111