Search code examples
c++templatesc++11referencetype-traits

What does T& mean for some template argument T?


For example

template<class T>
struct Ref
{
    using type = T&;
};

Is Ref<T>::type the same as std::add_lvalue_reference<T>::type for all possible template arguments? E.g. int, int&, and int&&?

I just read the source code for std::add_lvalue_reference<T>. Quite sure they are equivalent.
If they are, we can save some space by simply writing T& instead.


Solution

  • Table 53 in [meta.trans.ref] - definition of add_lvalue_reference:

    If T names an object or function type then the member typedef type shall name T&; otherwise, if T names a type “rvalue reference to T1” then the member typedef type shall name T1&; otherwise, type shall name T.

    Now recall the rules for reference collapsing:

    If […] a type template-parameter (14.3.1) […] denotes a type TR that is a reference to a type T, an attempt to create the type “lvalue reference to cv TR” creates the type “lvalue reference to T […]

    So the answer is yes:

    • For objects or functions the condition is trivially met. It's just T&, no reference collapsing involved.

    • For rvalue references, an lvalue reference to the type referred-to, T1, is created.

    • For lvalue references the exact reference type is preserved.