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?

2
  • 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. Commented Feb 27, 2018 at 3:32
  • Also read this. Commented Feb 27, 2018 at 3:33

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.