带有auto关键字的c++ 11函数定义

C++11 function definitions with auto keyword

本文关键字:函数 定义 c++ auto 关键字 带有      更新时间:2023-10-16

我很好奇在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
  1. 如果你需要在"->"之后指定返回类型(就像在C+11中一样)-在函数声明中有"auto"的意义是什么?这就好像在说:"这个函数可以返回任何东西,但实际上它只是这个类型"。呃?

  2. 如果你不需要在"->"之后指定返回类型(就像在c++ 14中一样):想象你没有函数的源代码,但是对象文件和头文件。你怎么知道函数返回什么(返回类型)?

到目前为止,函数声明中的"auto"似乎是编写不可读代码的另一种方式。好像在c++中没有足够的方法来实现它。

而在函数体内部"auto"是一个很好的"语法糖"。

还是我错过了什么?