How to create the equivalent of sub-type


In the Ada programming language, it's possible to declare a type or sub-type, like this:

type DAYS_OF_YEAR is range 1 .. 366;

type PERSONS_AGE is range 0 .. 120;

which in this case means unsigned integers that can only be in the given range.

At run-time, if a variable of that type is ever assigned a value out of its range, an exception is thrown.

What's the best way of implementing something similar in C++ 11?

Last edited on
It's not part of the standard library, but it seems to be a fan favorite for custom implementations:

ranged_type (2007 Dr.Dobbs article): http://www.drdobbs.com/cpp/ada-style-ranged-types-in-c/201001318

bounded_int (a boost candidate from 2008 http://rk.hekko.pl/constrained_value/ )

RangeConstrained (some guy's personal 2014 library) https://github.com/alkhimey/ConstrainedTypes

limited controlled vars (part of a larger 2011 library) http://snapwebsites.org/project/controlled-vars#Limited_Controlled_Variables

bounded::integer from a C++Now 2014 presentation: https://bitbucket.org/davidstone/bounded_integer - hey, this one had the last commit 2 days ago

I am sure you can find a lot more examples
Last edited on
Thanks Cubbi, your answer was very helpful.

Tony
Last edited on
Topic archived. No new replies allowed.