我可以防止将 int typedef 隐式转换为 int 吗?

Can I prevent implicit conversion of an int typedef to int?

本文关键字:int 转换 typedef 我可以      更新时间:2023-10-16

我希望以下内容不编译。

typedef int relative_index_t;  // Define an int to only use for indexing.
void function1(relative_index_t i) {
  // Do stuff.
}
relative_index_t y = 1; function1(y);  // I want this to build.
int x = 1; function1(x);               // I want this to NOT build!

有什么办法可以做到这一点吗?

>你不能用typedef这样做。

请改用以下内容:

enum class relative_index_t : int {};

用法示例:

int a = 0;
relative_index_t b;
b = (relative_index_t)a; // this doesn't compile without a cast
a = (int)b; // this too

或者如果您更喜欢C++式演员表,请关注:

int a = 0;
relative_index_t b;
b = static_cast<relative_index_t>(a);
a = static_cast<int>(b);

您也可以使用BOOST_STRONG_TYPEDEF。
(@AlexanderPoluektov学分(

一种技术借鉴了Modula-2的不透明类型:

typedef struct {
              int  index;
        } relative_index_t;

这可能足以防止使用 int 进行转换。 它还允许另一个成员变量允许其他功能,如年龄、序列号生成、边界检查等。