2

I've recently begun using the std::reference_wrapper class. When replacing certain uses of primitive references, I noticed that I did not have to use the get() function to pass the reference_wrappers as parameters to functions that take a normal reference.

void foo(const T& a);
//...
T obj;
std::reference_wrapper<const T> ref(obj);
foo(ref);  //works!
//foo(ref.get()); also works, but I expected that it would be required

How does std::reference_wrapper implicitly convert to a primitive reference when it is passed into a function?

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
Elliot Hatch
  • 1,038
  • 1
  • 12
  • 26

2 Answers2

6

reference_wrapper includes (ยง20.8.3):

// access
operator T& () const noexcept;

This is a conversion operator, and since it isn't specified as explicit, it allows implicit conversion from reference_wrapper<T> to T&.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
5

It overloads this conversion operator:

operator T& () const;

http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/get

Pubby
  • 51,882
  • 13
  • 139
  • 180