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
?
You should use it when the required type of y
is:
expr
. If it was the same then auto
would be more concise.auto &
or other modifications of the type of expr
that auto
can express.and one of the following:
decltype
would save you defining one.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.