C++ decltype
April 26, 2020 by Jane

I have recently been studying the new features of C++ 11

The keyword "decltype" came up.

What is decltype? It evaluates expressions to types and is used in mostly generic or template programming. The cv-qualifiers are maintained if they are part of the expression. (cv-qualifiers are properties such as const and volatile)

For example if we were to write an addition function that accepts different types like so:

template <typename T, typename T2>

T add(T a, T2 b) {

    return a + b;

}

It's hard to say what the return type will be if we're adding a float and an integer etc there might be unpredictable casting.

E.g.

add( 1, 2.2) --> gives us 3

add( 2.2, 1) --> gives us 3.2

However by using "decltype" we can always be sure it will return the more precise cast

auto add(T a, T2 b) -> decltype(a+b) {
    return a + b;
}

We can even have finer control over the return type:

auto min(T a, T2 b) -> decltype(a < b ? a : b) {
    return a + b;
}

In general decltype will not be used in day-to-day programming but more in generics/template library construction where a lot of the times the types have to be inferred.