C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Specify that argument to function cannot be an rvalue

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Sun, 9 Oct 2022 09:02:15 -0400
On Sun, Oct 9, 2022 at 8:54 AM Andrey Semashev via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> On 10/9/22 15:30, Arthur O'Dwyer via Std-Proposals wrote:
> > On Sat, Oct 8, 2022 at 5:58 PM Jason McKesson wrote:
> > On Sat, Oct 8, 2022 at 5:46 PM Frederick Virchanza Gotham wrote:
> > >
> > > [...] left it as non-const though, because I didn't want someone
> > to be able to do
> > > the following:
> > >
> > > short unsigned k = 7u;
> > > Func(k);
> > >
> > > I didn't want the implicit conversion from rvalue to "reference to
> > const".
> >
> >
> > FWIW, I think the status quo is fine (and you've now seen at least one,
> > maybe two ways of dealing with the problem if you really need to). But
> > as a data point / fun story, this came up in somebody (else)'s C++ Pub
> > Quiz recently (maybe CppNorth? I forget the details), and was discussed
> > briefly on the cpplang Slack.
> > https://godbolt.org/z/c63hjo4xK <https://godbolt.org/z/c63hjo4xK>
> >
> > void f(int&&) { puts("int"); }
> > void f(double&&) { puts("double"); }
> >
> > int main() {
> > int i = 1;
> > double d = 2;
> > f(i); // prints "double"
> > f(d); // prints "int"
> > }
> >
> > Completely unsurprising, when you think about how this overload set
> > needs to work:
> > https://godbolt.org/z/4E7hsrqfz <https://godbolt.org/z/4E7hsrqfz>
> >
> > void f(const char *&) { puts("pointer"); }
> > void f(std::string&&) { puts("string"); }
> >
> > int main() {
> > const char *p = "hello";
> > f(p); // prints "string"
> > }
>
> The last example prints "pointer".
>

Ha. In my defense, it's still before 9am here. :) I meant `const char*&&`:
https://godbolt.org/z/jKjP86bTa


> The first example I'd call *anything but* unsurprising. Maybe for
> language lawyers it is expected, but for most normal people it isn't.
>

That's how it ended up in a Pub Quiz! But it's unsurprising *when you
think about how the overload set needs to work for strings*, and then
realize that C++ treats "implicit conversion to string" and "implicit
conversion to float" essentially the same way. (Because C++ treats *every*
type essentially the same way: you don't get different behavior in the
first example just because the types involved in the first example happen
to be "primitive" types.)

–Arthur

Received on 2022-10-09 13:02:27