std::optional<bool> opt(false);
assert(opt); // true even though *opt is false!
http://en.cppreference.com/w/cpp/utility/optional std::optional<bool> opt(false);
assert(opt); // true even though *opt is false!
http://en.cppreference.com/w/cpp/utility/optional enum Bool
{
True,
False,
FileNotFound
};
http://thedailywtf.com/articles/What_Is_Truth_0x3f_If a developer wants a yes/no/unknown type, an enum class is better suited for the job. This forces them to explicitly compare values instead of relying on an implicit boolean conversion.
The function computing that is probably served really well by returning an optional bool.
std::optional is an useful wrapper because a simple "bool + object" would call constructors and all when that might be undesirable.
IMO, ternary logic belongs as an enum class, to require developers to be explicit about what branches are taken for what values.
I think it may be worth mentioning that std::unique_ptr can be used to "manage" non-heap pointers as well.
An optional pointer is a weird tri state thing where you can have empty or a null pointer or a non-null pointer.
There are a bunch of other parts of the C++ code base that are the same way. The most notorious one I can think of is std::declval, which just makes no sense whatsoever unless it appears inside another template.
That isn't true, as std::optional are explicitly converted to bool to signal whether the object stores a value.
http://en.cppreference.com/w/cpp/utility/optional/operator_b...
std::optional<unsigned> opt = firstEvenNumberIn(text);
if (opt)Good luck with that.
In that case you need to pay attention to what you're doing. Semantically you'd be altering your code to convert a function that always returns a value into a function that maybe won't return it. How do you expect to replace a type with a wrapper that maybe won't wrap that type and still assume you won't need to check if a return value exists?
That would be like replacing a reference with a pointer and then forgetting to check if the pointer is null. Making this mistake has nothing to do with luck and has everything to do with incompetence, and no language specs saves you from that.
If the optional wouldn't be an implicit boolean, you'd see compile errors on the locations you forgot to change (even if you use type inference).