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 typedef
ed 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 typedef
ed 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 class
es instead of typedef
s) , 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
Post a Comment