如何在模板 class 中使用 lambda 作为 STL 比较方法?

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

我正在尝试实现一个 priority_queue,其中包含 A<T> 个对象并使用自定义 Compare method/type。根据reference example,这是我的代码:

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);
};

但我收到以下错误:

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

我试图定义 lamda static,但它导致了一个新的语法错误:

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

你能帮我解决一下吗?

更新:我正在使用 VS2013

没有必要使 cmp 静态化。相反,您可以这样做:

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;
};

不要忘记包含 <functional> 才能正常工作。

对我来说static 完美

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

对于非静态...通过 using 怎么样?

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

lType cmp = lType{};