6

How can I compare two std::reference_wrappers by the references they hold? I want to see if the references of two std::reference_wrappers are equal or not.

Edit: Sorry from confusion. I meant how to get the addresses of referents and compare them.

Shibli
  • 5,879
  • 13
  • 62
  • 126
  • `r1.get() == r2.get()` – David G Jun 06 '14 at 00:49
  • 3
    Do you want to compare the addresses of the objects the `reference_wrapper`s refer to (as the title suggests), or compare the objects themselves for equality (as the body of the question suggests)? – Praetorian Jun 06 '14 at 01:05

2 Answers2

11

The get() member function returns a reference to the element referred to. You can then take the addresses of the referents directly.

std::addressof(r1.get()) == std::addressof(r2.get())
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 2
    What? No. References do not have addresses. Here you are getting the addresses of the _referees_, and I'm not even sure that this is what the OP intended to ask for. – Lightness Races in Orbit Jun 06 '14 at 00:54
  • 2
    @LightnessRacesinOrbit sorry poor wording on my part. And I am quite sure OP wanted to compare *addresses* because of the question title. – Brian Bi Jun 06 '14 at 01:59
5

The member function std::reference_wrapper::get will return the reference it holds. You can then compare the two referenced objects with:

const auto& a = ref_a.get();
const auto& b = ref_b.get();
if (a == b) {
    // …
}

The above will, of course, call operator== on the two objects (if the type is a class type).

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 2
    @LightnessRacesinOrbit I felt like helping one of the few guys [that actually listens](http://stackoverflow.com/a/24049899/493122) and tries to improve his code. – Shoe Jun 06 '14 at 00:55
  • He obviously _doesn't_ listen, otherwise he still wouldn't be posting RTFM helpdesk questions. – Lightness Races in Orbit Jun 06 '14 at 09:22