Posted on

decltype is used to get the type of a expression

Considering the following function

typedef<typename T1, typename T2>
T1 add(T1 a, T2 b) {
    return a + b;
}

For the following 2 invocations

add(1, 1.5);
add(1.5, 1);

The results will be different,

2
2.5

To solve this problem, we can use decltype, the return type should be type of the expression a + b.

typedef<typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a + b) {
    return a + b;
}

References

  1. https://www.youtube.com/watch?v=j6FG28KlgMI

Leave a Reply

Your email address will not be published. Required fields are marked *