问题
In the following, is &&
a universal reference ?
template <class Function = std::greater<int> > void f(Function&& f = Function());
回答1:
The term universal reference
is a made up term by Scott Meyers to make a distinction between normal rvalue references, i.e. int&&
and rvalue references in template code, i.e. T&&
. This is important because of the reference collapsing rules that come into play with template code, so this term is used to aid in teaching. The reason it is called a unversal reference
is because it can bind to anything.
Just keep in mind that there is no such thing as a universal reference
in the C++ language, Function&&
is a rvalue reference as far as the language is concerned. However, yes, in Scott Meyer's made up terminology, Function&&
is a universal reference
in your example.
回答2:
is && a universal reference ?
Sort of. Like the Easter bunny and Santa Claus, there is actually no such thing as a universal reference (sorry if I spoiled that for you). The term universal reference does not show up in the standard. It is term coined by Scott Meyers to describe templated rvalue references when "special deduction rules" are active.
What you show is valid code. And the special deduction rules do apply in this case. That is, when you pass an lvalue argument A
to f
, Function
will deduce to A&
. So by Scott's definition, yes, Function
is a "universal reference."
回答3:
Looks like it, std::forward<Function>
correctly forwards the argument type when called in your function.
来源:https://stackoverflow.com/questions/15181741/can-a-defaulted-template-type-be-universal-reference