C++11 decltype in real conditions

January 18, 2017 · 1 minute to read · C++, C++11

Today, I would like to talk about the usage of decltype specifier. Appeared in C++11, this new keyword “returns” the type of a variable or an expression. It is similar to auto keyword but not in all situations.

Examples

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627
#include <iostream>

using namespace std;

template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u)
{
    return t + u;
}

template<typename T, typename U>
void mul(T t, U u)
{
    decltype(t * u) m = t * u;
    cout << "is float: " << std::is_same<float, decltype(m)>::value << endl;
    cout << m << endl; // do something
}

int main()
{
    cout << add(4, 5.5) << endl;

    mul(6, 1.f/4);
    mul(6, 1/2);

    return 0;
}

Thanks to decltype, compiler can now deduce return type from template.

I will update this article from time to time, with new examples.

References