When should I use decltype(x) instead of auto to declare the type of a variable?

decltype becomes handy when you need to return some unknown type, which is evaluated during compilation:

template<class A, class B>
void MultiplyAB(A a, B b, decltype(a*b)& output)
{
    output = a * b;
}

Additionally, if you don’t like the way the output is handled by a reference, then you can also use the late-specified return type (and also use the decltype):

template<class A, class B>
auto MultiplyAB(A a, B b) -> decltype(a*b)
{
    return a * b;
}

All of this, and more, is described by B. Stroustrup in the C++ FAQ.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)