[英]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 . 所以它意味着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. 我知道重载赋值运算符本身是不可能的,因为它适用于赋值左侧的对象,而标准不允许带有两个参数的friend函数。
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: 如果通过重载任何其他运算符或使用一些特殊技巧无法做到这一点,除非通过调用Wrapper类提供的get方法,除非通过调用Wrapper类提供的get方法,否则将如何实现:
int y = x.get();
Why not just provide an implicit conversion to T
为什么不直接向
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
. 这将导致赋值运行,因为编译器将尝试将赋值的右侧转换为
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. 例如,现在可以将
Wrapper<T>
实例作为T
参数传递。 That may or may not work for your particular scenario 这可能适用于您的特定情况,也可能不适用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.