Consider this snippet of code, which uses the common idiom of having a function template construct an instance of a class template specialized on a deduced type, as seen with
There isn't a formal definition of "universal reference", but I would define it as:
A universal reference is a parameter of a function template with type [template-parameter]
&&
, with the intent that the template parameter can be deduced from the function argument, and the argument will be passed either by lvalue reference or by rvalue reference as appropriate.
So by that definition, no, the T&& v
parameter in foo
's constructor is not a universal reference.
However, the entire point of the phrase "universal reference" is to provide a model or pattern for us humans to think about while designing, reading, and understanding code. And it is reasonable and helpful to say that "When make_foo
calls the constructor of foo
, the template parameter T
has been deduced from the argument to make_foo
in a way that allows the constructor parameter T&& v
to be either an lvalue reference or an rvalue reference as appropriate." This is close enough to the same concept that I would be fine moving on to the claim: "When make_foo
calls the constructor of foo
, the constructor parameter T&& v
is essentially a universal reference."
Yes, both uses of std::forward
will do what you intend here, allowing member v_
to move from the make_foo
argument if possible or copy otherwise. But having make_foo(my_str)
return a foo
, not a foo
, that contains a copy of my_str
is quite surprising....