C ++中的多个整数类型的类 [英] Multiple Integer-type classes in C++
问题描述
我经常发现自己使用整数来表示不同空格中的值。例如...
I often find myself using Integers to represent values in different "spaces". For example...
int arrayIndex;
int usersAge;
int daysToChristmas;
理想情况下,我想为这些类型索引 和天,这应该防止我不小心混合起来。 Typedef是从documnentation角度的帮助,但是不是类型安全足够。
Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a help from a documnentation perspective, but aren't type-safe enough.
我已经尝试过包装类,但最终为我的喜好太多样板。有没有一个简单的基于模板的解决方案,或者可能在Boost中准备好的东西?
I've tried wrapper classes, but end up with too much boilerplate for my liking. Is there a straightforward template-based solution, or maybe something ready-to-go in Boost?
编辑:有几个人谈到了边界检查在他们的答案。这可能是一个方便的副作用,但不是一个关键要求。特别是,我不只是想防止超出范围的分配,而是在不适当类型之间的分配。
Several people have talked about bounds-checking in their answers. That maybe a handy side-effect, but is NOT a key requirement. In particular, I don't just want to prevent out-of-bound assignments, but assignments between "inappropriate" types.
推荐答案
您可以尝试BOOST_STRONG_TYPEDEF。从 boost / strong_typedef.hpp
:
You could try BOOST_STRONG_TYPEDEF. From boost/strong_typedef.hpp
:
// macro used to implement a strong typedef. strong typedef
// guarentees that two types are distinguised even though the
// share the same underlying implementation. typedef does not create
// a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new type named D
// that operates as a type T.
这篇关于C ++中的多个整数类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!