c++ - C++ 中的类型安全类型定义

标签 c++ types type-safety

我想在我的 C++ 程序中使用 typedef 之类的东西来增强类型安全性。

举个例子,假设我有两个函数

void function1(unsigned idOfType1);
void function2(unsigned idOfType2);

然后我会错误地将 idOfType2 传递给 function1,反之亦然。在这种情况下,我希望编译器给我一个错误。我知道我可以将这些 un​​signed 包装在一个结构中,但是我必须提供一个字段名称并使用 . 来访问它们,这有点不方便。有什么好办法吗?

编辑:据我所知 typedef 不适用于此目的,因为它只是类型的简写,不会用于类型检查。

最佳答案

使用 Boost strong typedef :

typedef creates an alias for an existing type. It does not create a new type that can be used for matching either function or template parameters...

Usage of BOOST_STRONG_TYPEDEF addresses this...

BOOST_STRONG_TYPEDEF is a macro which generates a class named "name" wraps and instance of its primitive type and provides appropriate conversion operators in order to make the new type substitutable for the one that it wraps.

关于c++ - C++ 中的类型安全类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588009/

相关文章:

generics - 如何将 "Encodable"绑定(bind)到类型参数?

types - 类型检查不适用于 Luau 中的通用字符串键?

java - @SafeVarargs 是否适合此方法的注释?

java - 您如何测试通用 API 的类型安全性?

haskell - 正确使用类和类型

Java/Scala 以类型安全的方式获取 Field 引用

c++ - C++ 中的 Stackdump 不显示堆栈跟踪

c++ - glfw 不创建窗口

c++ - 从函数中删除动态大小的数组

c++ - Boost C++ http post 获取服务 : How to make more than one run on same port?