Special case: optional<bool> and optional<T*>
This lesson highlights a case where using std::optional is not recommended.
While you can use optional on any type, you need to pay attention when trying to wrap boolean or pointers.
optional<bool>
- what does it model? With such a construction, you have a tri-state bool. If you need it, then maybe it’s better to look for a real tri-state bool like boost::tribool.
What’s more, it might be confusing to use such type because optional<bool>
converts to bool
. Also, if there’s a value inside then accessing that value returns bool
.
Likewise, you have a similar ambiguity with pointers:
Get hands-on with 1400+ tech skills courses.