类型安全typedef在C ++ [英] typesafe typedef in C++
问题描述
我想在我的C ++程序中使用类似typedef来提高类型安全性。
I would like to use something like typedef in my C++ programs to enhance type safety.
例如,假设我有两个函数
As an example, suppose I have two functions
void function1(unsigned idOfType1);
void function2(unsigned idOfType2);
那么我可以错误地将idOfType2传递给function1,反之亦然。我想编译器给我一个错误在这种情况下。我知道我可以包装这些unsigned在一个结构,但然后我必须提供一个字段名称并使用。
访问它们,这是有点不方便。这有什么好的方法吗?
then I can mistakenly pass idOfType2 to function1 and vice versa. I want the compiler to give me an error in this case. I am aware that I could wrap these unsigned in a struct, but then I'd have to give provide a field name and use .
to access them, which is slightly inconvenient. Is there a good way around this?
编辑:据我所知 typedef
因为它只是一个类型的简写,不会用于类型检查。
As far as I know typedef
will not work for this purpose as it is just a shorthand for a type and will not be used for type checking.
推荐答案
在这里帮助你。我不能立即想到一个更好的方法,但是如果你用你的包装在一个结构/类选项,你可以使用转换操作符,以消除成员方法或函数调用。
As you say, a typedef won't help you here. I can't think of a better way immediately, however if you go with your wrapping in a struct/class option you could use a conversion operator to eliminate the member method or function call.
例如:
struct WrappedType
{
operator type()
{
return _value;
}
type _value;
}
我不是说这是 - )
I'm not saying this is the way to do it mind you ;-)
这篇关于类型安全typedef在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!