C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sat, 8 Oct 2022 17:56:59 -0400
On Sat, Oct 8, 2022 at 5:46 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> This year I wrote a function something like as follows:
>
> long unsigned Func(long unsigned &arg)
> {
> return arg + 5u;
> }
>
> You can see that 'arg' isn't altered by this function, and so the
> function parameter type could be made a reference to const. I 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".
>
> I think there should be a way of telling the compiler to disallow this
> implicit conversion when passing arguments to a function,

You can always delete all alternative overloads:

template<typename T>
void Func(T const&) = delete;

Template functions have lower overload priority than non-template
functions that exactly match the specified types. So you'll only get a
problem if an exact match doesn't happen.

Received on 2022-10-08 21:58:16