为什么不能使用带有模板的 lambda

Why does not work with lambda with template

auto bind2nd = [] < auto func_object,auto second_arg>(){
    return [=](auto&& first_arg){
        return func_object(first_arg,second_arg);
    };
};

auto h =bind2nd.template operator()<std::greater<int>(),5>();

编译结果:

<source>:9:60: error: no matching function for call to '<lambda()>::operator()<std::greater<int>(), 5>()'

    9 | auto x =bind2nd.template operator()<std::greater<int>(),5>();

      |                                                            ^

<source>:3:16: note: candidate: 'template<auto func_object, auto second_arg> <lambda()>'

    3 | auto bind2nd = [] < auto func_object,auto second_arg>(){

      |                ^

<source>:3:16: note:   template argument deduction/substitution failed:

<source>:9:60: error: type/value mismatch at argument 1 in template parameter list for 'template<auto func_object, auto second_arg> <lambda()>'

    9 | auto x =bind2nd.template operator()<std::greater<int>(),5>();

      |                                                            ^

<source>:9:60: note:   expected a constant of type 'auto', got 'std::greater<int>()'

<source>:9:60: note:   ambiguous template argument for non-type template parameter is treated as function type

我想将 lambda 与模板一起使用,但它不起作用。

但我可以 运行 :

auto x =[]<auto t>(){
    return t;
};

auto test = []<auto func_object,auto second_arg>(){
    return [=](auto&& first_arg){
        return func_object.template operator()<second_arg>();
    };
};
auto z =test.template operator()<x,5>();

int main(){
    std::cout<<z(5);
}   

它将打印 5。

在模板中使用 lambda 的正确方法是什么?如何解决这个问题?

作为模板参数,std::greater<int>() 被解析为函数类型(一个不带参数且 returns class 类型 std::greater<int> 的函数)。这是您可以使用花括号帮助编译器区分的地方:

auto h = bind2nd.template operator()<std::greater<int>{}, 5>();