gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:38:20 25 4
gpt4 key购买 nike

我想声明我自己的数字类型,就像 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com