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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With