C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 19 Jun 2023 10:32:09 +0100
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
}

Received on 2023-06-19 09:32:21