简体   繁体   English

decltype 中的 C++11 lambda

[英]C++11 lambda in decltype

For the following code:对于以下代码:

auto F(int count) -> decltype([](int m) { return 0; }) 
{                                                               
    return [](int m) { return 0; };                                  
}

g++ 4.5 gives the errors: g++ 4.5 给出了错误:

test1.cpp:1:32: error: expected primary-expression before 'int'
test1.cpp:1:32: error: expected ')' before 'int'

What is the problem?有什么问题? What is the correct way to return a lambda from a function?从函数返回 lambda 的正确方法是什么?

You cannot use a lambda expression except by actually creating that object- that makes it impossible to pass to type deduction like decltype.您不能使用 lambda 表达式,除非通过实际创建该对象 - 这使得无法像 decltype 那样传递类型推导。

Ironically, of course, the lambda return rules make it so that you CAN return lambdas from lambdas, as there are some situations in which the return type doesn't have to be specified.具有讽刺意味的是,当然,lambda 返回规则使您可以从 lambda 返回 lambda,因为在某些情况下不必指定返回类型。

You only have two choices- return a polymorphic container such as std::function , or make F itself an actual lambda.你只有两个选择——返回一个多态容器,比如std::function ,或者让 F 本身成为一个实际的 lambda。

auto F = [](int count) { return [](int m) { return 0; }; };

something like this fits your needs?这样的东西符合您的需求吗?

#include <functional>

std::function<int(int)> F(int count)
{                                                               
    return [](int m) { return 0; };                                  
}

With C++14, you can now simply omit the return type:使用 C++14,您现在可以简单地省略返回类型:

auto F(int count)
{
    return [](int m) { return 0; };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM