3

std::reference_wrapper is a standard library that wraps a reference in a copyable, assignable object.

My view is that it has a weird design and seems like a hack to trick classes that store objects by value to believe that they are copying a value instead of storing a reference.

It also seems like a "tag" to pass by reference.

Without getting into any controversy about the semantics of the class:

What I find particularly puzzling is that it implements operator()(...) (forwarding it to the internal reference).

Does anybody know why it implements such a member specifically? I mean, it could implement many other operators, like ==, or [], so why () only?

With that criterion, it should implement any common operator +, ==, <, [], swap (not to mention, any arbitrary member like `.size(), if that were possible in the language).

A possibility that I imagine is that std::reference_wrapper is many times used to store functions, but it seems just odd, and in that case reference_function would have been a better name.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
alfC
  • 14,261
  • 4
  • 67
  • 118
  • Per the same documentation you linked to, is there something unclear about the statements "*If the stored reference is Callable, std::reference_wrapper is callable with the same arguments*" and "*This function is available only if the stored reference points to a Callable object*"? – Remy Lebeau Apr 27 '22 at 04:10
  • @RemyLebeau, thanks, yes that is the specification that requires that. It could have equally have said "If the stored reference is RandomAccesable, std::reference_wrapper is accessible with the same argument (operator[])". I was looking why they stopped with `operator()`. – alfC Apr 27 '22 at 04:13
  • 3
    [Related](https://softwareengineering.stackexchange.com/a/380636): "*Indeed, the genesis of what became `std::reference_wrapper` is `boost::bind`. `bind` is a tool that captures things and forwards them to a function, altering its signature. A user might want to capture some things as references, or they may want to capture some things as values. **This requires tagging specific parameters to `bind` with some syntax, and `boost::reference_wrapper` is what makes that tagging work**.*" So, it was biased towards Callables from its inception. – Remy Lebeau Apr 27 '22 at 04:23

0 Answers0