Skip to content

Commit

Permalink
Handle comparison between std::expected and nullptr
Browse files Browse the repository at this point in the history
  • Loading branch information
rollbear committed Jun 30, 2024
1 parent 8f36c45 commit 2498c74
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
* Fixed issue with std::expected causing compilation error. Thank you
@subbota-a for reporting

v47 2024-01-01

* Coroutines are conditionally supported by the __cpp_impl_coroutine
Expand Down
29 changes: 29 additions & 0 deletions include/trompeloeil/mock.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,19 @@
#include <coroutine>
#endif


#if TROMPELOEIL_CPLUSPLUS >= 202211L
# if __has_include(<expected>)
# include <expected>
# endif
# if defined(__cpp_lib_expected)
# define TROMPELOEIL_HAS_EXPECTED 1
# else
# define TROMPELOEIL_HAS_EXPECTED 0
# endif
#else
#define TROMPELOEIL_HAS_EXPECTED 0
#endif
#ifndef TROMPELOEIL_CUSTOM_ATOMIC
#include <atomic>
namespace trompeloeil { using std::atomic; }
Expand Down Expand Up @@ -1008,6 +1021,22 @@ template <typename T>
return is_null(t.get());
}

#if TROMPELOEIL_HAS_EXPECTED
template <typename T, typename E>
constexpr
bool
is_null(const std::expected<T, E>& e)
{
if constexpr (requires { e.value() == nullptr; }) {
return e == nullptr;
}
else
{
return false;
}
}
#endif

template <typename T>
void
print(
Expand Down
30 changes: 30 additions & 0 deletions test/compiling_tests_14.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5167,4 +5167,34 @@ TEST_CASE_METHOD(
REQUIRE(okReports.empty());
}

#if TROMPELOEIL_HAS_EXPECTED
TEST_CASE_METHOD(
Fixture,
"C++23: is_null with expected",
"[C++23][is_null]")
{
WHEN("value type of expected is not comparable to null")
{
THEN("is null is false")
{
REQUIRE_FALSE(trompeloeil::is_null(std::expected<int,int>{}));
}
}
AND_WHEN("value type is comparable with nullptr but false")
{
THEN("is null is false")
{
REQUIRE_FALSE(trompeloeil::is_null(std::expected<const void*, int>{"foo"}));
}
}
AND_WHEN("value type is comparable with nullptr and true")
{
THEN("is null is true")
{
REQUIRE(trompeloeil::is_null(std::expected<const void*, int>{}));
}
}
}
#endif

#endif /* TROMPELOEIL_CPLUSPLUS > 201103L */

1 comment on commit 2498c74

@subbota-a
Copy link

@subbota-a subbota-a commented on 2498c74 Jun 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that one more case should be tested.

  AND_WHEN("value type is comparable with nullptr but expected contains an error")
  {
    THEN("is null is false")
    {
      REQUIRE_FALSE(trompeloeil::is_null(std::expected<const void*, int>{std::unexpect, 0}));
    }
  }

Please sign in to comment.