Enforce strong type checking in C (type strictness for typedefs)

后端 未结 9 2441
遇见更好的自我
遇见更好的自我 2020-11-29 03:43

Is there a way to enforce explicit cast for typedefs of the same type? I\'ve to deal with utf8 and sometimes I get confused with the indices for the character count and the

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 04:09

    With C++11 you can use an enum class, e.g.

    enum class char_idx_t : unsigned int {};
    enum class byte_idx_t : unsigned int {};
    

    The compiler will enforce an explicit cast between the two types; it is like a thin wrapper class. Unfortunately you won't have operator overloading, e.g. if you want to add two char_idx_t together you will have to cast them to unsigned int.

提交回复
热议问题