Trailing return types are most useful in two main scenarios.
Firstly, they’re useful when writing function templates where the return type depends on the template parameters. For example:
template <typename T1, typename T2>
auto Multiply(T1 x, T2 y) -> decltype(x * y) {
return x * y;
}
Here, the return type is deduced based on the types of x and y, which aren't known until the template is instantiated.
Secondly, trailing return types are useful when the return type is hard to express before the function parameters. This often occurs with complex types or when using decltype
:
auto CreateComplexObject(int param)
-> decltype(Object(param)) {
return Object(param);
}
In this case, expressing the return type before the function name would be cumbersome.
Outside of these scenarios, using trailing return types is a style choice. Some programmers prefer them for consistency or readability, but they aren't strictly necessary. Traditional return type syntax is fine in most cases.
Answers to questions are automatically generated and may not have been reviewed.
An alternative syntax for defining function templates, which allows the return type to be based on their parameter types