I am using a decimal library. However, I've encapsulated it within a class so I can swap implementations etc.
So it has one member like this:
class Decimal
{
public:
decimal::Decimal _value;
};
I'd prefer not to have to overload every single arithmetic operator just because I'm wrapping the underlying type.
In other words, I'd like to be able to do this:
Decimal a(6);
Decimal b(5);
Decimal c = a + b;
instead of:
Decimal a(6);
Decimal b(5);
Decimal c(a._value + b._value);
Is this possible?
I am using a decimal library. However, I've encapsulated it within a class so I can swap implementations etc.
So it has one member like this:
class Decimal
{
public:
decimal::Decimal _value;
};
I'd prefer not to have to overload every single arithmetic operator just because I'm wrapping the underlying type.
In other words, I'd like to be able to do this:
Decimal a(6);
Decimal b(5);
Decimal c = a + b;
instead of:
Decimal a(6);
Decimal b(5);
Decimal c(a._value + b._value);
Is this possible?
Share Improve this question asked Feb 5 at 17:44 intrigued_66intrigued_66 17.2k51 gold badges129 silver badges206 bronze badges 4 |1 Answer
Reset to default 3I'd prefer not to have to overload every single arithmetic operator just because I'm wrapping the underlying type.
If you want to use encapsulation, then unfortunately that is exactly what you need to do, as you have to define exactly what operators your wrapper itself supports, regardless of what it is wrapping internally.
On the other hand, if all of the implementation types you want to work with provide equivalent constructors and operators, then a simpler type alias may work instead, as @TedLyngmo suggested, eg:
#if (some condition)
using Decimal = decimal::Decimal;
#elif (some other condition)
using Decimal = other_decimal::OtherDecimal;
#endif
using Decimal = decimal::Decimal;
orusing Decimal = other_decimal::OtherDecimal;
– Ted Lyngmo Commented Feb 5 at 17:53operator==
andoperator<
, there is a group of stencils that will define the auxiliary operators:!=, <=, >,
and>=
. – Thomas Matthews Commented Feb 5 at 18:07