Trailing return type explained

In computer programming, a subroutine (a.k.a. function) will often inform calling code about the result of its computation, by returning a value to that calling code.The data type of that value is called the function's return type.

In the C++ programming language, a function must be declared.The C++ function's return type is specified as a part of declaring that function.A trailing return type, a syntax feature available since C++11, is like a traditional return type, except that it is specified in a different location.

Syntax

An ordinary return type is specified before the function's name.In this example of traditional C++ code, the return type of HasMultipleItems is bool:class CClass ;

bool CClass::HasMultipleItems A trailing return type is specified after the parameter list, following -> symbols:class CClass ;

auto CClass::HasMultipleItems -> bool

Distinction from other language features

In modern C++, the meaning of the auto keyword will depend on its context:

)

Rationale

Consider the task of programming a generic version of int Add(const int& lhs, const int& rhs) { return lhs + rhs; }.A proper expression of this function's return type would use the two formal parameter names with decltype: decltype(lhs + rhs).But, where a return type is traditionally specified, those two formal parameters are not yet in scope.Consequently, this code will not compile:// This will not compiletemplatedecltype(lhs + rhs) Add(const TL& lhs, const TR& rhs) The formal parameters are in scope, where a trailing return type is specified:templateauto Add(const TL& lhs, const TR& rhs) -> decltype(lhs + rhs)

See also

References

[1] [2] [3] [4]

Notes and References

  1. Web site: C++0x Suffix Return Types . The C++ Resources Network . cplusplus.com . 1 March 2021.
  2. Web site: Function declaration . C++ Reference . cppreference.com . 1 March 2021.
  3. Web site: Functions (C++) . Microsoft Corporation . Microsoft C++, C, and Assembler . 1 March 2021.
  4. Book: Stroustrup, Bjarne . Bjarne Stroustrup . . Addison-Wesley . 2013 . Fourth . 978-0-321-56384-2.