Overloading the assignment operator when the object is on the right side of the job

Given the following code:

template <typename T> struct Wrapper { T value; Wrapper(T val) : value(val) {} } int main() { Wrapper<int> x(42); int y = x; // need solution for y = x.value return 0; } 

Is there any way to implement the assignment

 int y = x; 

so that means y = x.value.

I know that overloading the assignment operator itself is impossible, since it is applied to the object on the left side of the assignment function and a friend with two arguments that are not allowed by the standard.

If this is not possible, by overloading any other statement or using some special tricks, how you implement it, with the exception of calling the get method provided by the Wrapper class, for example:

 int y = x.get(); 
+7
c ++ operator-overloading
source share
1 answer

Why not just provide an implicit conversion to T

 operator T() { return value; } 

This will cause the assignment to function, because the compiler will try to convert the right side of the job to T Implicit conversion will succeed

Please note that this will cause other conversions to work beyond the destination. For example, you can now pass instances of Wrapper<T> as T parameters. This may or may not work for your specific scenario.

+7
source share

All Articles