Reputation: 91
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?
Upvotes: 3
Views: 3699
Reputation: 7838
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;
Upvotes: 7