3 ms·
I don’t see it being reasonable at all. If you need more than two values, use an enum?
by Matheus28 8y ago
I don’t see it being reasonable at all. If you need more than two values, use an enum?
- deleted 8y ago[deleted]
- cpeterso 8y agoThat's a good point. If need a bool variable, there is a decent chance you will need more values later. In that case, an enum is more extensible and the names are more descriptive. Like the classic "Daily WTF?": enum Bool { True, False, FileNotFound }; http://thedailywtf.com/articles/What_Is_Truth_0x3f_ http://thedailywtf.com/articles/What_Is_Truth_0x3f_
- Koshkin 8y agoWell there you go: your 'True' resolves to 0 (and 'False' to 1). So, please don't do this. bool exists for a reason, and so does std::optional.
- Matheus28 8y agoI think you misunderstood my point (or exaggerated it a bit to make that reference). Regardless, Let me add my suggestion for those wanting to use std::optional<bool>: 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.
- rocqua 8y agoIs the first number in a string even or odd? The function computing that is probably served really well by returning an optional bool.
- deleted 8y ago[deleted]
- avip 8y agoTernary logic (Yes/No/idk) is one of the most common use-cases for std::optional I've seen.
- Matheus28 8y agoThe vastly more common use-case I've seen is when you want to have an optional value, but don't want the heap allocation that comes with std::unique_ptr. 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.
- Koshkin 8y agoheap allocation that comes with std::unique_ptr I think it may be worth mentioning that std::unique_ptr can be used to "manage" non-heap pointers as well.