带有auto关键字的c++ 11函数定义
C++11 function definitions with auto keyword
我很好奇在c++ 11中使用auto关键字。
对于函数定义,必须写函数的返回类型:
auto f (int x) -> int { return x + 3; }; //success
auto f (int x) { return x + 3; }; //fail
,但在这个例子中,它们都可以使用:
auto f = [](int x) { return x + 3; }; //expect a failure but it works
auto f = [](int x) -> int { return x + 3; }; // this is expected code
谢谢。
在c++ 11中,lambda表达式可以省略它的返回类型,如果它可以推断出准确的返回类型而没有歧义。但是,此规则不适用于正则函数。
int f() { return 0; } // a legal C++ function
auto f() -> int { return 0; } // a legal C++ function only in C++11
auto f() { return 0; } // an illegal C++ function even if in C++11
-
如果你需要在"->"之后指定返回类型(就像在C+11中一样)-在函数声明中有"auto"的意义是什么?这就好像在说:"这个函数可以返回任何东西,但实际上它只是这个类型"。呃?
-
如果你不需要在"->"之后指定返回类型(就像在c++ 14中一样):想象你没有函数的源代码,但是对象文件和头文件。你怎么知道函数返回什么(返回类型)?
而在函数体内部"auto"是一个很好的"语法糖"。
还是我错过了什么?
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义