我想以下不能编译.
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!
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这个目标?
你不能这样做typedef.
请改用以下内容:
enum class relative_index_t : int {};
Run Code Online (Sandbox Code Playgroud)
用法示例:
int a = 0;
relative_index_t b;
b = (relative_index_t)a; // this doesn't compile without a cast
a = (int)b; // this too
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢C++风格的演员表,请关注以下内容:
int a = 0;
relative_index_t b;
b = static_cast<relative_index_t>(a);
a = static_cast<int>(b);
Run Code Online (Sandbox Code Playgroud)
您也可以使用BOOST_STRONG_TYPEDEF.
(致@AlexanderPoluektov的积分)