user2298352 user2298352 - 1 year ago 68
C++ Question

Quick int-like type with invariant? C++

Is there a quick way to define a type that has an int member and an invariant in the constructor...


class Age {
Age(int age) {
Expects(0 <= age && age <= 125);
age_ = age;
int age_;

...and then have the type as usable as an int?

Age a1 {32};
Age a2 {40};
cout << "Combined ages: " << a1 + a1;
Age a3 = a1 * 2;
// ...etc. etc.

(Or is the only way to override all operators?)

Thanks, John.

Answer Source

You can add operator int() returning the value and it will be useable as an integer.