TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 230 subscribers
Post #25176 23
std::optional equality comparison operator seems broken for nested optionals

While chasing a bug in a program I found out that equality comparison operator T vs optional<T> is broken if T is optional<U>. It is broken in worst possible way - it compiles but for some values it returns wrong results!

Here is an example:
https://godbolt.org/z/v3bcTodGj

Since both sides of eq operator are specialization of optional then following overload is used:

operator==(const optional<T>& lhs, const optional<U>& rhs);

This operator is specified to return
lhs.has_value() != rhs.has_value() ? false :
(lhs.has_value() == false ? true : *lhs == *rhs)

This falls apart for above scenario since lhs has value while rhs no value.
Since this is a case of optional<T>{} == T{} comparison, such scenario should be handled separately. Here is my attempt at fixing it:
https://godbolt.org/z/Yq3nM4xn4

This is rather not a proper fix, since it will still break for cases like optional<optional<short>>{} == optional<int>{}, and the internal if-constexpr instead should probably compare the nestedness of lhs and rhs optional.

I didn't check but most likely the same problem applies to relational operators.



https://redd.it/1tafsep
@r_cpp
godbolt.org Compiler Explorer - C++ (x86-64 gcc (trunk)) int main() { using T = std::optional<int>; std::optional<T> opt = T(); T val = opt.value(); assert(opt == val); }
More from @r_cpp
  1. Oct 3, 2026Teodorescu - [https://youtu.be/vVFFW6hoG1Y](https://youtu.be/vVFFW6hoG1Y) * Demystifying C…
  2. Oct 3, 2026New C++ Conference Videos Released This Month - September 2026 (Updated To Include Videos…
  3. Oct 3, 2026HPX 2.0.0 RC1 Released! – The HPX Project HPX is a general-purpose parallel C++ runtime sy…
  4. Oct 3, 2026[PLDI'26] Persistent Iterators with Value Semantics https://www.youtube.com/watch?v=cq33C5…
  5. Oct 3, 2026A Cross-Toolkit Timeline Control, Wed, Oct 14, 2026, 6:00 PM https://www.meetup.com/utah-c…
  6. Oct 3, 2026Upcoming C++ User Group meetings in October https://meetingcpp.com/meetingcpp/news/items/U…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →