I am implementing a SI unit type system. To ensure units don’t leak in and out, I don’t want implicit conversion of any values to a unit, and vice-versa. However, it would be really convenient to be able convert 0 to my unit system, a bit like you can do with pointers, where 0 implicitly converts to a null pointer, but no other value does.
So my question is: can I replicate this kind of implicit conversion of 0 to null pointer? Or can I use it to my advantage to achieve the same thing?
For example what would you think of such a constructor?
constexpr unit_t(void*) : _value(0) { }
Note: the unit itself is in the type, not in the value.
Edit: Why casting from 0 to a unit?
The reason I want this, is to write algorithms that don’t know about units. For example, if you have a matrix of lengths and you want to invert it, you first compute its determinant, and if it’s not 0, then return the inverse (otherwise, this is an error).
So it would convenient to treat the 0 literal as a generic unit. And this is exactly what happens for pointers. You can type:
void* c = 0;
But not:
void f(int a) { void *c = a; }
The classical solution is to a pointer to some private type, that the user can’t name. That way, the only way he can get something that will match is through the implicit conversion from
0. (Usingvoid*means that practically anything which can convert to a pointer can be passed.)Note that this solution only works for integral constant 0. If the user wants to use
0.0(because he thinks thatdoublevalues make more sense), he can’t.You might also consider using a default constructor, so the client can simply write
SomeUnit()when he wants the default initialization.