From 1c60839a11010e214131d057b980f4873bcbe0e6 Mon Sep 17 00:00:00 2001 From: Anthony Calandra Date: Tue, 18 Jun 2019 16:01:59 -0400 Subject: [PATCH] Trailing return types. --- CPP11.md | 33 +++++++++++++++++++++++++++++++++ README.md | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/CPP11.md b/CPP11.md index b6080ad..2133f66 100644 --- a/CPP11.md +++ b/CPP11.md @@ -32,6 +32,7 @@ C++11 includes the following new language features: - [non-static data member initializers](#non-static-data-member-initializers) - [right angle brackets](#right-angle-brackets) - [ref-qualified member functions](#ref-qualified-member-functions) +- [trailing return types](#trailing-return-types) C++11 includes the following new library features: - [std::move](#stdmove) @@ -612,6 +613,38 @@ std::move(foo).getBar(); // calls `Bar Foo::getBar() &&` std::move(foo2).getBar(); // calls `Bar Foo::getBar() const&&` ``` +### Trailing return types +C++11 allows functions and lambdas an alternative syntax for specifying their return types. +```c++ +int f() { + return 123; +} +// vs. +auto f() -> int { + return 123; +} +``` +```c++ +auto g = []() -> int { + return 123; +}; +``` +This feature is especially useful when certain return types cannot be resolved: +```c++ +// NOTE: This does not compile! +template +decltype(a + b) add(T a, U b) { + return a + b; +} + +// Trailing return types allows this: +template +auto add(T a, U b) -> decltype(a + b) { + return a + b; +} +``` +In C++14, `decltype(auto)` can be used instead. + ## C++11 Library Features ### std::move diff --git a/README.md b/README.md index c6bf2ad..2030db1 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ C++11 includes the following new language features: - [non-static data member initializers](#non-static-data-member-initializers) - [right angle brackets](#right-angle-brackets) - [ref-qualified member functions](#ref-qualified-member-functions) +- [trailing return types](#trailing-return-types) C++11 includes the following new library features: - [std::move](#stdmove) @@ -1358,6 +1359,38 @@ std::move(foo).getBar(); // calls `Bar Foo::getBar() &&` std::move(foo2).getBar(); // calls `Bar Foo::getBar() const&&` ``` +### Trailing return types +C++11 allows functions and lambdas an alternative syntax for specifying their return types. +```c++ +int f() { + return 123; +} +// vs. +auto f() -> int { + return 123; +} +``` +```c++ +auto g = []() -> int { + return 123; +}; +``` +This feature is especially useful when certain return types cannot be resolved: +```c++ +// NOTE: This does not compile! +template +decltype(a + b) add(T a, U b) { + return a + b; +} + +// Trailing return types allows this: +template +auto add(T a, U b) -> decltype(a + b) { + return a + b; +} +``` +In C++14, [decltype(auto)](#decltypeauto) can be used instead. + ## C++11 Library Features ### std::move