c++c++11autodecltype

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


I see decltype(x) used inside macros where x is a variable name because the type of the object isn't known inside macros.

For example:

decltype(x) y = expr;

I could just have easily use auto instead of decltype. So what are those situations where decltype is needed for a variable type declaration instead of auto?


Solution

  • You should use it when the required type of y is:

    and one of the following:

    So for example replacing std::iterator_traits<RandomAccessIterator>::value_type with decltype(*it) might well be a win, although auto does often handle such cases.

    Subjective judgements enter at the point of "what is difficult", "what is long-winded" and "what is clear", but the rules of procedure can be the same regardless of how you make those judgements in specific cases.