如何在C ++中创建类型安全的int-enum?

时间:2022-05-14 14:48:20

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.

我需要创建许多介于整数和枚举之间的类。即有整数的算术,但也没有隐式转换为int。

2 个解决方案

#1


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

看看这个问题的答案 - BOOST_STRONG_TYPEDEF完全符合我的要求。

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

#2


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.

一种可能性是使用:: GetValue()方法创建一个定义为类的不变成员的“枚举”的类,以及使用重载来使用GetValue()来进行数学运算所需的数学运算。

#1


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

看看这个问题的答案 - BOOST_STRONG_TYPEDEF完全符合我的要求。

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

#2


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.

一种可能性是使用:: GetValue()方法创建一个定义为类的不变成员的“枚举”的类,以及使用重载来使用GetValue()来进行数学运算所需的数学运算。