Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

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.

like image 212
Roddy Avatar asked Nov 27 '22 06:11

Roddy


2 Answers

Boost does in fact have a library specifically for this type of thing! Check out the Boost.Units library.

like image 75
Ryan Fox Avatar answered Dec 05 '22 10:12

Ryan Fox


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.

like image 36
Joris Timmermans Avatar answered Dec 05 '22 10:12

Joris Timmermans