I often find myself using Integers to represent values in different "spaces". For example...
int arrayIndex;
int usersAge;
int daysToChristmas;
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?
EDIT: 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 does in fact have a library specifically for this type of thing! Check out the Boost.Units library.
One funky "hack" you could use is a template non-type parameter to create wrapper types. This doesn't add any bounds but it does allow to treat them as different types with only one set of boilerplate template code. I.e.
template<unsigned i>
class t_integer_wrapper
{
private:
int m_value;
public:
// Constructors, accessors, operators, etc.
};
typedef t_integer_wrapper<1> ArrayIndex;
typedef t_integer_wrapper<2> UsersAge;
Extend the template with lower and upper bounds or other validation as you like. Not pretty by a long shot though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With