Trailing Return Types

Using decltype with Trailing Return Types

How can I use decltype in combination with trailing return types?

Abstract art representing computer programming

The decltype keyword and trailing return types are often used together, especially in function templates. decltype allows you to inspect the type of an expression, which is useful for deducing return types.

Here's an example:

#include <iostream>

template <typename T1, typename T2>
auto Divide(T1 x, T2 y) -> decltype(x / y) {
  return x / y;
}

int main() {
  // int / int => int
  std::cout << Divide(10, 3);

  // double / int => double
  std::cout << Divide(10.0, 3);
}

In this template function, the return type is specified as decltype(x / y). This means that the return type will be the type of the expression x / y.

If we call Divide(10, 3), the return type will be int because 10 and 3 are both ints. But if we call Divide(10.0, 3), the return type will be double, because 10.0 is a double and double / int => double.

Using decltype like this lets us create generic functions that return the "correct" type based on the actual argument types.

Note that you can use decltype with a trailing return type even for non-template functions. This is useful if the return type is hard to write or depends on the function parameters in some way.

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:

  • 124 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