3 ms·
A pattern I've seen some people do is to just make an operator bool for the type that checks for a contextually-sensical invalid state that is also the default
by advael 2y ago
A pattern I've seen some people do is to just make an operator bool for the type that checks for a contextually-sensical invalid state that is also the default constructed state. This is absolutely a hack, and has lots of other implications, and I wouldn't recommend it, but I see why people do it, because it creates a low-overhead way of getting around the possibility of invalid stuff while not taking on the problems of lacking a default constructor
Personally, I like the simplicity of this kind of approach, but prefer to force consumers of the type to be more explicit. To that end, I really like having an constexpr bool operator! instead, so the same checks can be performed without making it easy to accidentally coerce your type into some shady arithmetic operations. You still can if you meant to, but it will be more obvious what you're doing and won't happen accidentally
- nemetroid 2y agoI’m not sure I follow entirely, but an explicit operator bool will only auto-convert in contexts where it makes sense, and not e.g. in arithemtic expressions. https://stackoverflow.com/questions/39995573/when-can-i-use-explicit-operator-bool-without-a-cast https://stackoverflow.com/questions/39995573/when-can-i-use-...
- advael 2y agoExplicit keyword seems reasonable too, I just like !! more than the verbosity of casting tbh. Totally aesthetic preference