user2298352 user2298352 - 1 year ago 91
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...

e.g.

class Age {
public:
Age(int age) {
Expects(0 <= age && age <= 125);
age_ = age;
}
private:
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download