Based on my understanding of Scott Meyers' "Effective Modern C++", a sample implementation of std::move
in C++14 is the following
template<typename T>
decltype(auto) move(T&& param) {
return static_cast<remove_reference_t<T>&&>(param);
}
Given the explanation of what a forwarding (or "universal") reference is, this implementation, I think, is pretty clear to me:
- the parameter
param
is of typeT&&
, i.e. an rvalue reference or lvalue reference (to whichever the type of the argument is), depending on whether the argument is an rvalue or lvalue in the caller; in other wordsparam
can bind both to rvalues and lvalues (i.e. anything); this is intended, sincemove
should cast anything to rvalue. decltype(auto)
is just the concise way to express the return type based on the actualreturn
statement.- the returned object is the same object
param
, casted to an rvalue reference (&&
) to whatever the typeT
is, once its deduced referenceness is stripped off (the deduction is done onT&&
, not on⋯<T>&&
).
In short, my understanding of the use of forwarding/universal references in the implementation of move
is the following:
- the forwarding/universal reference
T&&
is used for the parameter since it is intended to bind to anything; - the return type is an rvalue reference, since
move
is intended to turn anything to rvalue.
It'd be nice to know if my understanding is right so far.
On the other hand, a sample implementation of std::forward
in C++14 is the following
template<typename T>
T&& forward(remove_reference_t<T>& param) {
return static_cast<T&&>(param);
}
My understanding is the following:
T&&
, the return type, must be a forwarding/universal reference, since we wantforward
to return either by rvalue reference or by lvalue reference, hence type deduction takes place on the return type here (unlike what happens formove
, where type deduction takes place on the parameter side);- the type of
param
is an lvalue reference to whatever the typeT
is, once its deduced referenceness is stripped off.
My doubts are the following.
- The two instances of
forward
(two for each type on which is it called, actually) only differ for the return type (rvalue reference when an rvalue is passed, lvalue reference when an lvalue is passed), since in both casesparam
is of type lvalue reference to non-const
reference-lessT
. Isn't the return type something which does not count in overload resolution? (Maybe I've used "overload" improperly, here.) - Since the type of
param
is non-const
lvalue reference to reference-lessT
, and since an lvalue reference must be to-const
in order to bind to an rvalue, how canparam
bind to an rvalue?
As a side question:
- can
decltype(auto)
be used for the return type, as it is done formove
?
Aucun commentaire:
Enregistrer un commentaire