SigTerm
SigTerm

Reputation: 26429

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 would trigger compile error), while retaining all functionality provided by built-in type (operators).

One way to do it is to wrap each type into separate struct/class (and redefine all operators, etc).

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

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

Upvotes: 11

Views: 677

Answers (2)

Ajay
Ajay

Reputation: 18429

To trigger compiler errors, you may make both types as classes. In TypeA, make a conversion operator and/or constructor that converts to/from TypeB - and make these methods private.

This way, any conversion from TypeB to TypeA would call for the conversion function, and compiler would emit error that that method is private! Ensure that you may need to write few conversion operators/constructors from/to you want conversion to happen successfully. I mean, if you want conversion from float, you need to write constructor taking float and so on for other types.

You may write conversion operators, constructors in either TypeA or TypeB, and list of allowable conversions in these classes.

Upvotes: 0

BЈовић
BЈовић

Reputation: 64233

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

Upvotes: 4

Related Questions