my-server
← Wiki Redirected from Trailing-return-type

Trailing return type

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 <code>hasMultipleItems()</code> is <code>bool</code>:

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

Distinction from other language features

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

  • When used in a variable's definition (e.g., <code>auto x = 11;</code>), the <code>auto</code> keyword indicates type inference. The data type for that <code>x</code> will be deduced from its initialization. The return type of a function can also be inferred by using <code>auto</code> without specifying a trailing return type. For example:
  • On the other hand, there is no type inference in the <code>hasMultipleItems()</code> example on the previous section. That example only uses the <code>auto</code> keyword as a syntactic element, because a trailing return type is being used.

Rationale

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

A proper expression of this function's return type would use the two formal parameter names with decltype: <code>decltype(lhs + rhs)</code>. However, where a return type is traditionally specified, those two formal parameters are not yet in scope.

Consequently, this code will not compile:

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

See also

References