Łukasz Lew
Łukasz Lew

Reputation: 50268

How to create type-safe int - enum in C++?

I need to create many classes that are somewhere between integer and enum. I.e. have the arithmetics of integer but also are not implicitly converted to int.

Upvotes: 2

Views: 1258

Answers (2)

Roddy
Roddy

Reputation: 68033

Have a look at the answer to this question - BOOST_STRONG_TYPEDEF did exactly what I wanted.

// macro used to implement a strong typedef.  strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation.  typedef does not create
// a new type.  BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.

Upvotes: 4

Yes - that Jake.
Yes - that Jake.

Reputation: 17121

One possibility is to create a class with the "enums" defined as invariant members of the class with a ::GetValue() method and the mathematical operations you need to use overloaded to use GetValue() to do the math in question.

Upvotes: 1

Related Questions