diff --git a/include/wx/string.h b/include/wx/string.h index 77c8b0126b..57fbb56616 100644 --- a/include/wx/string.h +++ b/include/wx/string.h @@ -49,6 +49,11 @@ #endif #endif +// Check if C++20 three-way-comparison operator is available +#ifdef __cpp_impl_three_way_comparison + #include +#endif + #include "wx/afterstd.h" // by default we cache the mapping of the positions in UTF-8 string to the byte @@ -2288,6 +2293,19 @@ public: friend bool operator>=(const wxString& s1, const wxString& s2) { return s1.Cmp(s2) >= 0; } +#ifdef __cpp_impl_three_way_comparison + friend auto operator<=>(const wxString& s1, const wxString& s2) + { + const int cmp = s1.Cmp(s2); + if (cmp < 0) + return std::strong_ordering::less; + else if (cmp > 0) + return std::strong_ordering::greater; + else + return std::strong_ordering::equal; + } +#endif + friend bool operator==(const wxString& s1, const wxCStrData& s2) { return s1 == s2.AsString(); } friend bool operator==(const wxCStrData& s1, const wxString& s2) diff --git a/tests/strings/strings.cpp b/tests/strings/strings.cpp index 7e0d2466b4..c37a22149f 100644 --- a/tests/strings/strings.cpp +++ b/tests/strings/strings.cpp @@ -453,6 +453,21 @@ TEST_CASE("StringCompare", "[wxString]") CHECK( wxString("!").Cmp("z") < 0 ); } +#ifdef __cpp_lib_three_way_comparison +TEST_CASE("StringCompareThreeWay", "[wxString]") +{ + // test that operator<=> works and compares by string contents + + wxString a(wxT("bar")); + wxString b(wxT("bar")); + wxString c(wxT("baz")); + + CHECK((a <=> b) == std::strong_ordering::equal); + CHECK((a <=> c) == std::strong_ordering::less); + CHECK((c <=> a) == std::strong_ordering::greater); +} +#endif // __cpp_lib_three_way_comparison + TEST_CASE("StringCompareNoCase", "[wxString]") { wxString s1 = wxT("AHH");