Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading assignment operator when the object is on the right-hand side of the assignment

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 a way to implement the assignment

int y = x;

so that it means y = x.value .

I know that overloading the assignment operator itself is not possible because it applies to the object on the left side of the assignment and friend function with two arguments is not allowed by the standard.

If this is not possible by overloading any other operator, or by using some special tricks, how would you implement this, except by invoking the get method provided by the Wrapper class such as:

int y = x.get();
like image 339
Diggy Avatar asked Aug 12 '13 20:08

Diggy


1 Answers

Why not just provide an implicit conversion to T

operator T() { return value; } 

This will cause the assignment to function because the compiler will attempt to convert the right side of the assignment to T. The implicit conversion will allow that to succeed

Note that this will cause other conversions to work besides assignment. For example it will now be possible to pass Wrapper<T> instances as T parameters. That may or may not work for your particular scenario

like image 175
JaredPar Avatar answered Oct 27 '22 00:10

JaredPar