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++?