3

So I've found this fancy stuff std::reference_wrapper in C++11 which I found could be useful in future program development. I played with it for a bit and I thought it could replace good-old reference in some cases for better usage, until I bumped into the following error:

#include <iostream>
#include <functional>

class testbench {
public:
    int ownerid = 5;
    bool camper = false;
};

class testing {
public:
    testing(testbench &x);
    int quack = 3;
    std::reference_wrapper <testbench> camper;
};

testing::testing(testbench &x):camper(x) {
}

int main() {
    testbench tempo;
    testing test_a (tempo);
    std::cout << test_a.camper.ownerid;
}

this would cause an error in gcc (I'm using Code::Blocks as Editor and gcc as compiler)

'class std::reference_wrapper<testbench>' has no member named 'ownerid'

If the line

    std::reference_wrapper <testbench> camper;

is changed to :

    testbench &camper;

Then everything is worked as I expected.

How do I fix this, or is it just my misunderstanding std::reference_wrapper as a general improvement of reference?

kiyah
  • 1,502
  • 2
  • 18
  • 27
  • 1
    Cast them explicitly. "There is no additional level of syntactical indirection. Pointers have to be dereferenced to obtain an lvalue to the object they refer to; `reference_wrappers` have an implicit **conversion operator** and can be called like the object they wrap." - [source](https://stackoverflow.com/questions/26766939/difference-between-stdreference-wrapper-and-simple-pointer). – user202729 Feb 27 '18 at 03:32
  • [Also read this](https://stackoverflow.com/questions/11799540/trigger-cast-operator-on-use-of-the-dot-operator). – user202729 Feb 27 '18 at 03:33

1 Answers1

5

Your understanding is wrong. std::reference_wrapper can implicitly cast to a T& (in your case, testbench) but when you use the member accessor (test_a.camper.ownerid) it's operating on the camper, not the object it's wrapping.

You can either do a cast or use the get member function. This is untested, but I think it'll work:

test_a.camper.get().ownerid;
Stephen Newell
  • 7,330
  • 1
  • 24
  • 28