Post

C++ Tips : Trailing Return Type

Trailing Return Type: auto add(int a, int b) -> int

C++ Tips : Trailing Return Type

My C++ Tips

Trailing Return Type


Trailing Return Type

  • A way to specify the return type of a function after the parameter list.
  • Useful when the return type depends on the types of the parameters
1
2
3
4
auto add(int a, int b) -> int 
{
    return a + b;
}

Why it’s important?

  • When the return type depends on the parameter types.
1
2
3
4
5
6
7
8
9
10
11
12
13
template <typename T, typename U>
decltype(a * b) multiply(T a, U b) 
{   // ERROR: 'a' and 'b' not yet declared
    return a * b;
}

template <typename T, typename U>
auto multiply(T a, U b) -> decltype(a * b) 
{
    // OK. Because decltype(a * b) needs a and b to already exist in the scope, 
    // which only happens after the parameter list.
    return a * b;
}
This post is licensed under CC BY 4.0 by the author.