Let's say I have:
template<class T>
struct NodeBase
{
T value;
NodeBase(T &&value)
: value(value) { }
};
and I inherit from it:
template<class T>
struct Node : public NodeBase<T>
{
Node(T &&value)
: NodeBase( WHAT_GOES_HERE (value)) { }
};
Should WHAT_GOES_HERE
be std::move
or std::forward<T>
? Why?
Since in the implementation of the constructor of Node<T>
it is unknown whether T
is a plain type (i.e. not a reference), or a reference,
std::forward<T>(value)
is suitable.
std::forward<T>(value)
is the right choice whenever it isn't known whether T &&
binds to an rvalue or an lvalue. This is the case here because in the constructor we don't know whether T &&
is equivalent to U &&
for some plain type U
, or equivalent to U & &&
.
It doesn't matter whether T
is deduced in the function call that uses std::forward
or determined at a different time (such as in your example, where T
is determined at the time when the Node
template is instantiated).
std::forward<T>(value)
will call the inherited constructor in the same way as if the base class constructor had been called directly by the caller. I.e., it will call it on an lvalue when value
is an lvalue, and on an rvalue when value
is an rvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With