Monday, March 28, 2011

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.

From stackoverflow
  • 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.

  • 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.
    

0 comments:

Post a Comment