-1

I really need a new datatype in my application, which will only store numbers from -10 to 10. Is there a way to create a datatype with specific values, which will raise an error if the value is invalid? I used:

typedef int digit;

The thing that happens is a new datatype which is actually int is created. I also tried this:

typedef int{-10 > int value < 10} digit;

but it raised this:

exit status 1
main.cpp:3:12: error: expected unqualified-id before '{' token
typedef int{-10 > int value < 10} digit;
           ^
main.cpp:3:35: error: 'digit' does not name a type; did you mean 'div_t'?
typedef int{-10 > int value < 10} digit;
                                    ^~~~~
                                  div_t
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Andrii Chumakov
  • 279
  • 3
  • 12

1 Answers1

1

C++ does not have such a feature. It would be quite nice in certain situations, but non-trivial to provide in the language (and inefficient to use, to some degree).

You can create a class that wraps int and does its own bounds checking (or however you want the type to behave). You would then have to wrap all the arithmetic operations too. Not too onerous, but a bit of a pain in the neck. And, again, not efficient (every single arithmetic operation will need a branch!).

Generally we just use an int and do our checks in our code logic when needed, at a higher level. I can't make specific suggestions without knowing your use case.

Here's an example that does half of it.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055