最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Is it possible to directly access a one-member class without explicit operator? - Stack Overflow

programmeradmin1浏览0评论

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
  • 5 Since you want to be able to swap implementations, how do the implementations differ? You could just use a type alias if there isn't any difference in how the types can be used. using Decimal = decimal::Decimal; or using Decimal = other_decimal::OtherDecimal; – Ted Lyngmo Commented Feb 5 at 17:53
  • 1 To both of you, I think I'd rather alias it for now! Thanks anyway – intrigued_66 Commented Feb 5 at 17:54
  • 1 you might be interested in boosts strongtypedef. To see what boilerplate is needed, or to simply use it – 463035818_is_not_an_ai Commented Feb 5 at 17:58
  • Review the Boost library. They have templates that will define auxiliary functions for you. For example, if you define operator== and operator<, there is a group of stencils that will define the auxiliary operators: !=, <=, >, and >=. – Thomas Matthews Commented Feb 5 at 18:07
Add a comment  | 

1 Answer 1

Reset to default 3

I'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
发布评论

评论列表(0)

  1. 暂无评论