Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict implicit conversion of typedef'ed types?

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 typedefed 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 typedefed types, and if yes, then how?

like image 533
Ruslan Avatar asked Sep 30 '22 23:09

Ruslan


1 Answers

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 classes instead of typedefs) 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.

like image 100
gha.st Avatar answered Oct 03 '22 15:10

gha.st