我很好奇在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)
谢谢.
在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)
| 归档时间: |
|
| 查看次数: |
2540 次 |
| 最近记录: |