mardi 23 août 2016

Any way to define a "doubling" operator?

I have a class that represents a quantity that can only take on integer or half-integer values, and so stores its value internally as an integer that is twice the value. That is: a value of 0.5 is stored as 1, 1 as 2, 1.5 as 3, etc. Let's call it class A with a stored value int TwoA_.

This forces the A values to be properly integer or half-integer. Since I often need to use them as their true values, I have naturally made a cast to double operator that simply returns 0.5 * TwoA_.

However, very frequently I need to use twice the value. I thought it would be neat to code 2 * a (a being an object of type A) to directly return the value TwoA_ stored inside a.

Ideally, I'd like to make an operator that only does this when multiplied by 2 from the left. All other situations would be covered by the implicit cast.

Is there any way to do this in c++? I though of some sort of templated multiplication operator.

The simple solution of just defining

friend double operator*(int lhs, const A& rhs)
{ return (lhs == 2) ? rhs.TwoA_ : lhs * static_cast<double>(rhs); }

is not what I'm looking for. 2 * a is guaranteed to be an int (but generically an_int * a is not), and I would like to return an int.

This is a question of curiosity; if you only want to comment "why would you want to do that?" (or some variation thereof), please hold your tongue.

Aucun commentaire:

Enregistrer un commentaire