3

In the following, is && a universal reference ?

template <class Function = std::greater<int> > void f(Function&& f = Function());
Vincent
  • 57,703
  • 61
  • 205
  • 388

3 Answers3

7

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.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
3

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."

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
1

Looks like it, std::forward<Function> correctly forwards the argument type when called in your function.

Stephen Lin
  • 5,470
  • 26
  • 48