const applied to "universal reference" parameter
Asked Answered
A

0

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
Astrakhan answered 1/1, 2016 at 14:6 Comment(7)
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?Gorlin
What's the question? The code is ill-formed, just as the language rules say. x does not "suddenly become" anything.Unbeaten
@Gorlin Not sure what you mean by 'behavior', I just want to understand how does const affect universal references. as shown in examples above.Astrakhan
@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.Gorlin
@Mankarse, Oh, yes, I see now. I didn't compile the sample code at all. that makes sense now.Astrakhan
For anyone in the future reading this, this might explain: codesynthesis.com/~boris/blog/2012/07/24/…Astrakhan
@codekiddy: The article is a bit too dismissive. Const rvalue references can be useful for controlling overload sets, e.g. as for as_const.Unbeaten

© 2022 - 2024 — McMap. All rights reserved.