2

I want to create my own type that asserts some property at runtime, but otherwise behaves exactly as another type.

To get a better idea of what I mean, pretend for a moment unsigned integer types do not exist and I want to create my own type to represent them based on int.

I can do something like the following:

struct uint {
    int val;
    uint(int v) : val (v) {
         assert(v >= 0);
    }

But then I can't use my uint struct as a drop in replacement for int because I now have to call uint.val to access the value. I would like uint to behave exactly as an int but with the added runtime check during construction that the value is larger than zero.

Go has type embedding via

type myint {
    int
}
func New(int v) myint {
    // Check v > 0
}

and Rust has type aliasing

type myint = int;
impl myint {
    fn New(int v) -> myint {
        // check that v > 0
    }
}

Is it possible to achieve something like this in modern C++?

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
  • 3
    Lookup *strong typedefs*, they're a concept close to what you're trying to do and many of the implementation issues are the same. The answer is "not quite, but close enough". – Quentin Feb 22 '19 at 17:42
  • 3
    You could give `uint` an `operator int`. – NathanOliver Feb 22 '19 at 17:47
  • https://stackoverflow.com/questions/34287842/c-strongly-typed-using-and-typedef – stark Feb 22 '19 at 18:08
  • 1
    @stark interesting. Could be relevant. However, OP seems not so much interested in avoiding mixing types, but more in type validation - invariant enforcement – Christophe Feb 22 '19 at 18:34

0 Answers0