C++ Logo

std-proposals

Advanced search

Re: [std-proposals] explicit modifier for R-value references

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Mon, 19 Jun 2023 12:28:04 +0100
On Mon, 19 Jun 2023 at 10:32, Frederick Virchanza Gotham via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> In much the same way that a pointer can be const:
>
> int *const p;
>
> I propose that you can apply the 'explicit' modifier to an R-value
> reference:
>
> int &&explicit x;
>
> Consider the following code snippet:
>
> #include <iostream> // cout, endl
> #include <utility> // move
>
> using namespace std;
>
> void Func(int&) { cout << "L-value reference" << endl; }
>
> void Func(int const &) { cout << "L-value reference to const" << endl; }
>
> void Func(int&&) { cout << "R-value reference" << endl; }
>
> void Func(int const &&) { cout << "R-value reference to const" << endl; }
>
> int main(int argc, char **argv)
> {
> int val = 7;
>
> int &&explicit x = move(val);
>
> Func(x); // This prints 'R-value reference'
> }
>
> So the effect of the 'explicit' modifier on an R-value reference is
> that it gets treated as an R-value reference from that point onward
> (rather than being treated as an L-value reference).
>
> You could use it in function parameters as well:
>
> void SetVector( vector<int> &&explicit arg )
> {
> static vector<int> vec;
> vec = arg; // no need for 'move' here
> }
>
> Furthermore, when used with a template, it could eradicate the need
> for "std::forward" as follows:
>
> template<typename T>
> void SetVector( T &&explicit arg )
> {
> static T obj;
> vec = arg; // no need for 'forward' here
> }
>

That sounds feasible, and moderately useful. It wouldn't change the type,
correct (and especially not the function type)? - it would just change the
result of the value category computed by
http://eel.is/c++draft/expr.prim.id#unqual-3.sentence-6 .

If you're using it on universal references you'll have to say what it means
when applied to an lvalue reference as well.

Would it be applicable to class data members? Non-type template parameters?

Received on 2023-06-19 11:28:17