gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:35:47 24 4
gpt4 key购买 nike

我想在我的 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/

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