Suppose there're two types:
typedef unsigned short Altitude;
typedef double Time;
To detect some errors like passing time argument in position of altitude to functions at compile time I'd like to prohibit implicit conversion from Altitude
to Time
and vice-versa.
What I tried first was declaring an operator Altitude(Time)
without an implementation, but the compiler said that it must be a member function, so I understood that it's not going to work for a typedef
ed type.
Next I've tried turning one of these types into a class, but it appeared that the project extensively uses lots of arithmetic including implicit conversions to double
, int
, bool
etc., as well as passes them to and from streams via operator<<
and operator>>
. So despite this way allowed me to find the errors I was looking for, I didn't even try to make full implementation of the compatible class because it would take a lot of code.
So my question is: is there a more elegant way to prevent implicit conversions between two particular typedef
ed types, and if yes, then how?
A typedef
does nothing more than establish another name for an existing type.
Therefore your question boils down to whether you can disable implicit conversions between unsigned short
and double
, which is not possible in general.
Two ways exist to deal with this problem:
First, you can make Altitude
and Time
into their own types (read: define class
es instead of typedef
s) and ensure that they can be easily converted to and from their underlying numeric types - but not each other.
Second, you can ensure that whatever you do is protected by language constructs, e.g. if you have a function f
that should take an Altitude
a.k.a. unsigned short
, you can overload it with another function f
that takes an Time
a.k.a. double
and causes an error. This provides a better overload match and would thus prevent the implicit conversion in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With