some questions regarding ref

Hi, I want to have a few classes to be stored inside a vector by reference. I thought to use boost::ref for that purpose , instead of storing pointer. However I am facing some problem regarding the operator & . Here is a sample code which gives the problem, struct T2{ int x; T2(int x) :x(x){} }; int main(int argc,char** argv) { std::vector<boost::reference_wrapper<T2> > v; /// vector stores reference, rather than value. T2 t1 = 10; T2 t2 = 15; v.push_back(boost::ref(t1)); /// push ref to t1. v.push_back(boost::ref(t2)); ///push ref to t2. v[0].get().x = 5; ///get by ref & change. /// v[0].x = 5 ; this statement doesn't work! std::cout<<t1.x<<"\n"; ///change is reflected. return 0; } I am not sure why I have to use get for this purpose, while & operator is written for that purpose. Using MSVC 7.1 Even I face problem like this, struct T3{ T2 t2_; T3(int x) : t2_(x){} T2& operator&(){ return t2_; } }; std::vector<T3> v3; v3.push_back(T3(4)); v3.push_back(T3(5)); /// v3[0].x = 6; This doesn't work. (&v3[0]).x = 6; ///This works! Can anyone say a little detail about the problem ? -- Abir Basak, Member IEEE Software Engineer, Read Ink Technologies B. Tech, IIT Kharagpur email: abir@abirbasak.com homepage: www.abirbasak.com

On 2/3/07, abir basak <abirbasak@gmail.com> wrote:
struct T2{ int x; T2(int x) :x(x){} };
std::vector<boost::reference_wrapper<T2> > v; /// v[0].x = 5 ; this statement doesn't work!
I am not sure why I have to use get for this purpose, while & operator is written for that purpose.
That is not why operator& is written, because the compiler has NO WAY of knowing that your use of of the name "x" is referring to type T2, and so it doesn't know to invoke that conversion operator first. Instead, your code is trying to access member "x" of the reference_wrapper itself. The operator exists so you can initialize another reference from your reference_wrapper: T2 & t_ref = v[0]; t_ref = 5; In this context, the compiler knows to utilize the conversion operator, since you're assigning to a T2 reference. Chris
participants (2)
-
abir basak
-
Chris Uzdavinis