Trailing return type

Last updated

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.

Contents

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. [1] 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. [2] [3] [4]

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:

usingstd::vector;classMyClass{private:vector<int>items;public:boolhasMultipleItems(){returnitems.size()>1;}};

A trailing return type is specified after the parameter list, following -> symbols:

usingstd::vector;classMyClass{private:vector<int>items;public:autohasMultipleItems()->bool{returnitems.size()>1;}};

Distinction from other language features

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

autohasMultipleItems(){returnitems.size()>1;}

Rationale

Consider the task of programming a generic version of the following:

intadd(constint&lhs,constint&rhs){returnlhs+rhs;}

A proper expression of this function's return type would use the two formal parameter names with decltype: decltype(lhs + rhs). However, 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 compiletemplate<typenameL,typenameR>decltype(lhs+rhs)add(constL&lhs,constR&rhs){returnlhs+rhs;}

However, where a trailing return type is specified, the formal parameters are in scope:

template<typenameL,typenameR>autoadd(constL&lhs,constR&rhs)->decltype(lhs+rhs){returnlhs+rhs;}

See also

References

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