Search code examples
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:

    • different (or potentially different) from the type of expr. If it was the same then auto would be more concise.
    • similarly for auto & or other modifications of the type of expr that auto can express.

    and one of the following:

    • dependent on something in the surrounding code (i.e. not always the same type) and difficult to write using type traits or similar. This will tend to happen in template code. There might be a type trait that you can use to get the required type from the template parameters, but then again there might not so a use of decltype would save you defining one.
    • always the same type, (or dependent on template parameters in a way that is easy to express using existing type traits or similar) but the type is very long-winded to write and there is a much shorter and clear expression you can use instead.

    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.