Почему не работает лямбда с шаблоном - PullRequest
0 голосов
/ 27 мая 2020
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

Я хочу использовать лямбда с шаблоном, но он не работает.

Но я могу запустить это:

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.

Как правильно использовать лямбда-выражение с шаблоном и как решить эту проблему?

1 Ответ

3 голосов
/ 27 мая 2020

В качестве аргумента шаблона std::greater<int>() анализируется как тип функции (функция, которая не принимает аргументов и возвращает тип класса std::greater<int>). Здесь вы можете использовать фигурные скобки, чтобы помочь компилятору различать:

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