多个整数型类C ++ [英] Multiple Integer-type classes in C++
问题描述
我经常使用整数重新在不同的空间present价值发现自己。例如...
I often find myself using Integers to represent values in different "spaces". For example...
int arrayIndex;
int usersAge;
int daysToChristmas;
在理想情况下,我想有单独的类为这些类型的指数,年和天,这应该prevent我不小心把它们组合起来。类型定义是从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.
我试过包装类,但我喜欢太多的样板结束。有一个简单的基于模板的解决方案,或者在升压东西随时可以走?
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?
编辑:有几个人谈了自己的答案边界检查。也许一个方便的副作用,但不是关键要求。特别是,我不只是想prevent外结合的分配,但不合适类型之间的分配。
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。从升压/ 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屋!