Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of std::add_lvalue_reference and std::add_rvalue_reference?

Tags:

c++

What is the purpose of std::add_lvalue_reference and std::add_rvalue_reference?

It seems that using T &/T && does the same, as this successfully compiles:

#include <utility>

int main() {
    { using T = int;    static_assert(std::is_same_v<std::add_lvalue_reference_t<T>, T &>); };
    { using T = int &;  static_assert(std::is_same_v<std::add_lvalue_reference_t<T>, T &>); };
    { using T = int &&; static_assert(std::is_same_v<std::add_lvalue_reference_t<T>, T &>); };

    { using T = int;    static_assert(std::is_same_v<std::add_rvalue_reference_t<T>, T &&>); };
    { using T = int &;  static_assert(std::is_same_v<std::add_rvalue_reference_t<T>, T &&>); };
    { using T = int &&; static_assert(std::is_same_v<std::add_rvalue_reference_t<T>, T &&>); };
}
like image 495
geza Avatar asked Sep 06 '19 09:09

geza


1 Answers

void& is ill-formed. std::add_lvalue_reference<void> is void.

In general, add_lvalue_reference does not add reference to types if it is not possible. Per [meta.trans.ref]:

template <class T>
struct add_­lvalue_­reference;

If T names a referenceable type then the member typedef type names T&; otherwise, type names T. [ Note: This rule reflects the semantics of reference collapsing ([dcl.ref]). — end note ]

What is a referenceable type? Per [defns.referenceable], a referenceable type is

an object type, a function type that does not have cv-qualifiers or a ref-qualifier, or a reference type [ Note: The term describes a type to which a reference can be created, including reference types. — end note ]

like image 54
L. F. Avatar answered Oct 21 '22 08:10

L. F.