1

I've stumbled upon Scott Mayers article on universal references, link.

From what I understood universal reference, that is some type T&& can mean an rvalue or lvalue type in different contexts.

For example:

template<typename T>
void f(T&& param);               // deduced parameter type ⇒ type deduction;
                                 // && ≡ universal reference

In the above example depending on template parameter the T&& can be either an lvalue or rvalue, that is, it depends on how we call f

int x = 10;
f(x); // T&& is lvalue (reference)
f(10); // T&& is rvalue

However according to Scott, if we apply const to to above example the type T&& is always an rvalue:

template<typename T>
void f(const T&& param);               // “&&” means rvalue reference

Quote from the article:

Even the simple addition of a const qualifier is enough to disable the interpretation of “&&” as a universal reference:

Question: Why does const make an "universal" reference rvalue?

I think this is impossible because following code makes confusion then:

template<typename T>
void f(const T&& param);               // “&&” means rvalue reference

int x = 10;
f(x); // T&& is lvalue (reference) // how does 'x' suddenly become an rvalue because of const?
f(10); // T&& is rvalue // OK
codekiddy
  • 5,897
  • 9
  • 50
  • 80
  • 3
    What is the question? Are you asking for 'language-lawyer' justification of where this rule is specified in the standard, rationale for this behaviour, or an explanation for why your compiler doesn't exhibit the behaviour that Scott Meyers describes? – Mankarse Jan 01 '16 at 14:11
  • What's the question? The code is [ill-formed](https://ideone.com/osnNtR), just as the language rules say. `x` does not "suddenly become" anything. – Kerrek SB Jan 01 '16 at 14:15
  • @Mankarse Not sure what you mean by 'behavior', I just want to understand how does `const` affect universal references. as shown in examples above. – codekiddy Jan 01 '16 at 14:16
  • 2
    @codekiddy: I mean the 'behaviour' of 'failing to compile the code sample/failing to accept lvalue arguments to template function taking `(T const &&param)`'. `const` affects universal references in the way the Scott Meyers describes: it disables them. – Mankarse Jan 01 '16 at 14:21
  • @Mankarse, Oh, yes, I see now. I didn't compile the sample code at all. that makes sense now. – codekiddy Jan 01 '16 at 14:25
  • For anyone in the future reading this, this might explain: http://www.codesynthesis.com/~boris/blog/2012/07/24/const-rvalue-references/ – codekiddy Jan 01 '16 at 14:38
  • @codekiddy: The article is a bit too dismissive. Const rvalue references can be useful for controlling overload sets, e.g. as for [`as_const`](http://en.cppreference.com/w/cpp/utility/as_const). – Kerrek SB Jan 01 '16 at 19:25

0 Answers0