简体   繁体   English

当对象位于赋值的右侧时,重载赋值运算符

[英]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.

相关问题 赋值运算符(字符串)右侧的类型是什么? - What is the type of the right hand side of the assignment operator (string)? 下标是否在赋值运算符的右侧之前计算 - does subscript evaluate before the right hand side of assignment operator 在分配的右侧使用减量运算符是否有效的C ++? - Is using a predecrement operator on the right hand side of an assignment valid C++? 类实例在右侧的运算符重载 - Overloading of operators with class instance as right-hand side 输入迭代器是否只能在赋值的右手符号上被取消引用? - Can an input iterator be dereferenced only on the right-hand sign of an assignment? 当类包含指向另一个对象的指针时,重载赋值运算符 - overloading the assignment operator when the class contains pointer to another object 运算符重载赋值运算符 - Operator overloading assignment operator 分配运算符重载和自我分配 - Assignment Operator Overloading and Self Assignment 重载插入运算符:未找到采用“ unsigned int”类型的右侧操作数的运算符(或者没有可接受的转换) - Overloading Insertion Operator: no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion) STL std :: map operator []在赋值的右侧 - STL std::map operator[] when on the right side of assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM