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

iya*_*sar 2 c++ lambda c++11

我很好奇在C++ 11中使用auto关键字.

对于函数定义,必须编写函数的返回类型:

auto f (int x) -> int { return x + 3; }; //success
auto f (int x)  { return x + 3; }; //fail
Run Code Online (Sandbox Code Playgroud)

但在这个例子中,它们都可以工作:

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
Run Code Online (Sandbox Code Playgroud)

谢谢.

xml*_*lmx 5

在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
Run Code Online (Sandbox Code Playgroud)

  • @ErikW 尾随返回类型非常有用。假设您有“template<class T> class Vector”,并且想要实现向量标量乘法“multiply(Vector<T> const& v, X x)”。返回类型是什么?对于尾随返回类型,这很容易,因为我可以使用参数 `x` 和 `y`: `template<class T, class X> auto multiply(Vector<T> const& v, X x) -> Vector<decltype( v[0] * x)> {...}。 (4认同)
  • 注意它已被提议用于下一个规范(C++ 14),并且GCC 4.8已经使用选项`-std = c ++ 1y`实现了该功能. (2认同)