I have two classes (this is a, extract from my actual more complex case)
class ClUInt {
public:
ClUInt() : _i(2), _arr{1,2,3} {};
ClUInt(const unsigned int ui) : _i(ui) {};
private:
unsigned int _i;
double _arr[3];
};
class ClInt {
public:
ClInt() : _i(-2), _arr{-1,-2,-3} {};
ClInt(const int i) : ClInt() { _i = i; };
private:
int _i;
double _arr[3];
};
They are very similar, but one uses int
and the other unsigned int
for member _i
.
I want to overload operator<<
with, e.g.,
std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
cout << ci._i << endl;
cout << ci._arr[0] << endl;
return os;
}
Assume I want the "same" overload for both classes.
How can I write it only once, so it is easier to maintain? I thought of defining my own cast, but I am not sure it is the way to go...
Notes:
I think I have no chance of making the two classes share any part of an inheritance tree.
They could actually be
struct
s, so if privacy affects the answer, one can assume_i
and_arr
arepublic
.In the actual case, the two
struct
s have a larger number of "common" members which are signed/unsigned, respectively.