Trailing Return Types

When to Use Trailing Return Types in C++

In what situations is it beneficial or necessary to use trailing return types in C++ functions?

Abstract art representing computer programming

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.

This Question is from the Lesson:

Trailing Return Types

An alternative syntax for defining function templates, which allows the return type to be based on their parameter types

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Trailing Return Types

An alternative syntax for defining function templates, which allows the return type to be based on their parameter types

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved