c++ - How to restrict implicit conversion of typedef'ed types? -


suppose there're 2 types:

typedef unsigned short altitude; typedef double time; 

to detect errors passing time argument in position of altitude functions @ compile time i'd prohibit implicit conversion altitude time , vice-versa.

what tried first declaring operator altitude(time) without implementation, compiler said must member function, understood it's not going work typedefed type.

next i've tried turning 1 of these types class, appeared project extensively uses lots of arithmetic including implicit conversions double, int, bool etc., passes them , streams via operator<< , operator>>. despite way allowed me find errors looking for, didn't try make full implementation of compatible class because take lot of code.

so question is: there more elegant way prevent implicit conversions between 2 particular typedefed types, , if yes, how?

a typedef nothing more establish name existing type.

therefore question boils down whether can disable implicit conversions between unsigned short , double, not possible in general.

two ways exist deal problem:

first, can make altitude , time own types (read: define classes instead of typedefs) , ensure can converted , underlying numeric types - not each other.

second, can ensure whatever protected language constructs, e.g. if have function f should take altitude a.k.a. unsigned short, can overload function f takes time a.k.a. double , causes error. provides better overload match , prevent implicit conversion in case.


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -