Search⌘ K
AI Features

Automatic Return Type

Explore how automatic return type deduction works in C++ using auto and decltype keywords. Understand how function templates infer return types and how C++14 further simplifies this process to write cleaner and safer code.

We'll cover the following...

Using auto and decltype together, a function template is able to automatically deduce its return type. Here’s a function with a trailing return type:

C++
template <typename T1, typename T2>
auto add(T1 fir, T2 sec) -> decltype( fir + sec )
{
return fir + sec;
}

Rules

The syntax above follows a few rules:

  • auto: introduces the syntax for the delayed return type.

  • ...