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
?
auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a template function whose return type depends on the types of its template arguments.
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
decltype returnsIf what we pass to decltype is the name of a variable (e.g. decltype(x) above) or function or denotes a member of an object ( decltype x.i ), then the result is the type of whatever this refers to. As the example of decltype(y) above shows, this includes reference, const and volatile specifiers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With