0

I have a class that has a reference field that needs to be reassigned. But unlike pointer, it can't be null.

Requirements:

  • Reference syntax: field.foo() to invoke method, instead of field->foo();
  • Re-assignable: foo = new_val; // OK

Is it possible to model model this concept in C++?

random
  • 3,868
  • 3
  • 22
  • 39

1 Answers1

4

Yes. Use a std::reference_wrapper<T> instead of a raw reference.

Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58
  • Thanks. Did now known about it! Unfortunately it' not possible to call a method without a .get() – random Mar 22 '18 at 17:39
  • Looks like it's not possible : https://stackoverflow.com/questions/520035/why-cant-you-overload-the-operator-in-c – random Mar 22 '18 at 17:41
  • Yep. If `get()` is a deal breaker, then you're out-of-luck. Mind you, `reference_wrapper` is implicitly convertible to the associated reference type, so you can often avoid the `get()` in practice. – Peter Ruderman Mar 22 '18 at 18:54
  • Seem to be a well known problem in C++ : https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-operator-dot-proposal-bjarne-stroustrup – random Mar 22 '18 at 18:57