You should represent optional values using std::optional
. This is self documenting, other programmers know what they are about, and you avoid checking for invariant states of your own class (reduce complexity). It also uses STL conventions for value wrappers (same as iterators, smart pointers, etc.).
If you don't want to or simply can't use it, look at it's implementation and follow the same rules:
- implement a bool-conversion-operator (explicit)
- provide a method (like
std::optional::has_value()
) for use in templated methods
Note that if (...)
performs an explicit bool-cast on the statement. So generally there is no need for implicit conversions. In order to avoid trouble using overloads, you should always go for explicit conversion-operators.