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 int
s. 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.
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