【问题标题】:Why does not work with lambda with template为什么不能使用带有模板的 lambda
【发布时间】:2020-05-27 02:45:18
【问题描述】:
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 可以用作非类型模板参数类型。
  • @TedLyngmo:是的,谢谢你的回答。

标签: c++ templates lambda c++20


【解决方案1】:

作为模板参数std::greater&lt;int&gt;() 被解析为函数类型(一个不接受参数并返回类类型std::greater&lt;int&gt; 的函数)。这是您可以使用大括号来帮助编译器区分的地方:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多