我发现了一种以这种方式定义的功能:
http://en.cppreference.com/w/cpp/language/decltype
我从未见过用于定义函数的语法,任何人都能解释一下这个吗? 这似乎只适用于auto和decltype
#include <iostream>
using namespace std;
auto f = [](int a, int b)->int
{
return a * b;
};
/*
int f = [](int a, int b) //DOES NOT WORK
{
return a * b;
};
*/
int main()
{
int a = 2, b = 3;
cout<<f(a,b);
return 0;
}
当我们这样做时,我不确定以下函数是否使用了dectype:
->int
如果是,那怎么办?
答案 0 :(得分:3)
auto f = [](int a, int b)->int
{
return a * b;
};
f
这里是一个匿名类型的全局变量,包含在operator=
之后定义的匿名函数对象的实例。这样的匿名函数对象被称为 lambda ,它们可以出现在你可以拥有某个表达式的任何地方:
int main(int, char**) {
([](int a) {
cout << "lambda called with " << a << endl;
})(42);
return ([](int a, int b) { return a - 2 * b; })(42, 21);
}
这种lambda表达式的一般语法如下:
"["CAPTURE"]" PARAMETERS ["mutable"] [RETURN] { BODY }
CAPTURE
是一个零以上的列表
&
,按引用捕获&
表示通过引用=
表示按值 PARAMETERS
是您从函数中知道的常用参数列表,可选(自C ++ 14起)auto
和类型推导。
mutable
允许lambda改变其捕获的变量。
可选 RETURN
包含返回类型的规范,例如-> void
和BODY
包含任意表达式和语句。
注意这只是语法的粗略草图,但它应该让你开始。您可以在标准中找到有关lambdas的更多信息,搜索&#34; C ++ 11 lambda&#34;在Google上或例如here。
顺便说一下,一个lambda并不是什么怪异的东西,你可以认为你的f
是以下的粗略等同物,&#34;旧式&#34; C ++代码:
struct {
int operator()(int a, int b) const {
return a * b;
}
} f;
答案 1 :(得分:2)
使用时:
auto f = [](int a, int b)->int
{
return a * b;
};
f
的类型是lambda表达式的类型。它不是int
,是lambda表达式的返回类型。
就-> int
部分而言,这是唯一可用于显式指定lambda表达式的返回类型的语法。省略,返回类型由编译器使用标准指定的算法推导出来:
5.1.2 Lambda表达式
4如果 lambda-expression 不包含 lambda-declarator ,就好像 lambda-declarator 是()。如果 lambda-expression 不包含 trailing-return-type ,就好像 trailing-return-type 表示 以下类型:
- 如果复合语句的格式为
{
attribute-specifier-seqoptreturn
表达式; }
lvalue-to-rvalue转换(4.1),数组到指针转换(4.2)和函数到指针转换(4.3)之后返回表达式的类型;
- 否则,无效。
[示例:
auto x1 = [](int i){ return i; }; // OK: return type is int
auto x2 = []{ return { 1, 2 }; }; // error: the return type is void (a
// braced-init-list is not an expression)
- 结束示例]