Make typedefs incompatible

Situation:

typedef int TypeA; typedef int TypeB; 

I need to make TypeA incompatible with TypeB (so any attempt to assign TypeA to TypeB will result in a compilation error), while preserving all the functions provided by the built-in type (operators).

One way to do this is to wrap each type in a separate struct / class (and override all statements, etc.).

Is there any other, more "elegant" way to do this?

Third-party libraries are prohibited. C ++ 0x / C ++ 11x is not supported. (C ++ 2003 supported)

+6
source share
2 answers

The only way is to create a new type (using, for example, BOOST_STRONG_TYPEDEF ).

+4
source

To trigger compiler errors, you can create both types as classes. In TypeA make the conversion operator and / or constructor that will convert to / from TypeB , and make these methods private .

Thus, any conversion from TypeB to TypeA will call the conversion function, and the compiler will throw an error that this method is private! Make sure that you may need to write several conversion operators / constructors from / in order for the conversion to succeed. I want to say that if you want to convert from float , you need to write a constructor that accepts float , etc. For other types.

You can write conversion operators, constructors in TypeA or TypeB and a list of valid conversions in these classes.

0
source

Source: https://habr.com/ru/post/909068/


All Articles