简体   繁体   English

C ++通用右值重载

[英]C++ generic rvalue overload

I'm currently trying to refactor some code which uses a primitive type into something which I can tuck setters and getters into them. 我目前正在尝试将一些使用原始类型的代码重构为可以将setter和getter塞入其中的代码。 I wanted to make the change to the underlying code transparent, and at first I though C++'s operator overloads would help me out there. 我想对基础代码进行更改是透明的,但起初我虽然C ++的运算符重载可以帮助我。

Let's suppose I want to make an "augmented int " type, for instance, that can be treated just like a regular int , but allows for further action wherever I assign to it, and just assignment - all other properties of an int , such as adding with += , should be preserved. 让我们假设我想打一个“增强int ”类型,例如,可以治疗就像一个普通的int ,但允许采取进一步的行动,无论我分配给它,而只是分配-的所有其他属性int ,如与+=相加,应保留。

At first I first though that if I encapsulated the int inside some struct, and filled out the operator= overloads, I'd be set, like in the following example: 首先,尽管我首先将int封装在某个结构中,并填写了operator=重载,但我将被设置,如以下示例所示:

#include<iostream>

typedef struct PowerInt{
  int x;

  PowerInt(){
    cout << "PowerInt created\n";
    x = 0;
  }
  ~PowerInt(){
    cout << "PowerInt destroyed\n";
  }

  void operator=(int other){
    cout << "PowerInt received " << other << "\n";
    this->x = other;
  }
}PowerInt;

int main(){
  PowerInt a;
  a = 3;
  return 0;
}

The code compiles and runs as expected, but as soon as I try making anything else a regular int could do, like cout << a , or a += 2 , or even a simple int b = a; 代码可以按预期的方式编译和运行,但是一旦我尝试使常规int可以做其他事情,例如cout << aa += 2 ,甚至是简单的int b = a; assignment the compiler complains about the operators << and += missing. 分配时,编译器会抱怨缺少运算符<<+=

Fair enough; 很公平; I then though that, at least for << and "assigment = ", I could get by using some sort of "generic rvalue operator", or some kind of method which returns PowerInt.x wherever my a is used as an rvalue, automatically making expressions like int c = (a + 3); 但是我至少可以在<<和“ assigment = ”上使用某种“通用rvalue运算符”,或者某种将a用作rvalue的地方自动返回PowerInt.x的方法,使表达式如int c = (a + 3); and if (a == 3) {} valid. 并且if (a == 3) {}有效。

Problem is, I can't find a way to implement this idiom, and this mostly likely has to do with either my little understanding of how operator overloading works in C++, or some language feature I'm not yet aware of. 问题是,我找不到实现此惯用语的方法,这很可能与我对C ++中的运算符重载的工作方式了解得很少,或者我尚不了解的某些语言功能有关。 Is it possible to accomplish what I'm trying here? 是否可以完成我在这里尝试的工作?

If you want your PowerInt to be convertible to a normal int you can create a user-defined conversion operator: 如果希望PowerInt可转换为普通int ,则可以创建用户定义的转换运算符:

operator int() const
{
  return x;
}

Any operator that's not defined for PowerInt will then use the operator defined for a normal int . 任何未为PowerInt定义的运算符都将使用为普通int定义的运算符。

PS The typedef struct isn't necessary in C++. PS C ++中不需要typedef struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM