MVittiS MVittiS - 2 months ago 15
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

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.

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:

#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;
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);
and
if (a == 3) {}
valid.

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

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