MVittiS MVittiS - 1 year ago 86
C++ Question

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. 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.

Let's suppose I want to make an "augmented

" type, for instance, that can be treated just like a regular
, but allows for further action wherever I assign to it, and just assignment - all other properties of an
, such as adding with
, should be preserved.

At first I first though that if I encapsulated the
inside some struct, and filled out the
overloads, I'd be set, like in the following example:


typedef struct PowerInt{
int x;

cout << "PowerInt created\n";
x = 0;
cout << "PowerInt destroyed\n";

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

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;
assignment the compiler complains about the operators

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
wherever my
is used as an rvalue, automatically making expressions like
int c = (a + 3);
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. Is it possible to accomplish what I'm trying here?

Answer Source

If you want your PowerInt to be convertible to a normal int you can create a user-defined conversion operator:

operator int() const
  return x;

Any operator that's not defined for PowerInt will then use the operator defined for a normal int.

P.S The typedef struct isn't necessary in C++.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download