c++ - 在 C++ 中声明没有隐式转换的类型

标签 c++

我想声明我自己的数字类型,就像 unsigned int 一样,但我不希望这些类型被隐式转换。我首先尝试了这个: typedef unsigned int firstID; typedef unsigned int secondID;

但这并不好,因为这两种类型只是 unsigned int 的同义词,因此可以自由互换。

我希望这会导致错误:

firstID fid = 0;
secondID sid = fid; // no implicit conversion error

但这没关系:

firstID fid = 0;
secondID sid = static_cast<secondID>(fid); // no error

我的原因是函数参数是强类型的,例如:

void f( firstID, secondID ); // instead of void f(unsigned int, unsigned int)

我在寻找什么机制?

谢谢

最佳答案

也许是 BOOST_STRONG_TYPEDEF 形式 boost/strong_typedef.hpp会有帮助的。

关于c++ - 在 C++ 中声明没有隐式转换的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2200025/

相关文章:

c++ - 使用 Kerberos 身份验证模拟用户时建立 ODBC 连接

c++ - 只有 MSVC 能够编译这段代码

c++ - 比较两个图

c++ - 在 Windows 中运行 autotools (MinGW)

c++ - 如何调试DLLMain函数

c++ - 无法让 outfile 在 Windows 中使用 C++ 工作

c++ - invoke_result with member (operator[]) 函数

c++ - std::unique_ptr 是为数组分配内存的错误工具吗?

c++ - 是否可以在不手动将重写的克隆方法添加到 C++ 中的每个派生类的情况下克隆多态对象?

c++ - 使用指针和函数的 C++ 菜单