Skip to content

Commit

Permalink
Add operator== to TaggedUnion.hpp (#280)
Browse files Browse the repository at this point in the history
Co-authored-by: Matthieu Dubuget <[email protected]>
  • Loading branch information
ttamttam and Matthieu Dubuget authored Dec 6, 2024
1 parent dda27f9 commit 99f3f50
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
21 changes: 21 additions & 0 deletions include/rfl/TaggedUnion.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,27 @@ struct PossibleTags<TaggedUnion<_discriminator, Ts...>> {
template <class T>
using possible_tags_t = typename PossibleTags<T>::Type;

template <internal::StringLiteral _discriminator, class... Ts>
bool operator==(
const TaggedUnion<_discriminator, Ts...>& lhs,
const TaggedUnion<_discriminator, Ts...>& rhs
) {

return (lhs.variant().index() == rhs.variant().index()) &&
lhs.variant().visit(
[&rhs](const auto& l) {
return rhs.variant().visit(
[&l](const auto& r) -> bool {
if constexpr (std::is_same_v<std::decay_t<decltype(l)>, std::decay_t<decltype(r)>>)
return l == r;
else
return false;
}
);
}
);
}

} // namespace rfl

#endif // RFL_TAGGEDUNION_HPP_
69 changes: 69 additions & 0 deletions tests/json/test_tagged_union5.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>

#include <gtest/gtest.h>

namespace test_tagged_union5 {


struct Sa {
int a;
std::string b;
};

struct Sb {
std::string b;
int i;
};

template <typename T, typename... Ts>
concept OneOf = (std::is_same_v<T, Ts> || ...);

template <typename T>
bool operator==(const T& lhs, const T& rhs)
requires OneOf<T,
struct test_tagged_union5::Sa,
struct test_tagged_union5::Sb>
{
return rfl::to_named_tuple(lhs) == rfl::to_named_tuple(rhs);
}


using Tu = rfl::TaggedUnion<"tu",Sa,Sb>;

Tu v1 = Sa{.a = 1, .b = "b" };
Tu v2 = Sa{.a = 1, .b = "b" };
Tu v3 = Sa{.a = 1, .b = "bc" };
Tu v4 = Sb{.b = "s", .i = -2};

TEST(json, test_tagged_union5) {
ASSERT_TRUE(v1 == v1);
ASSERT_TRUE(v1 == v2);
ASSERT_TRUE(v1 != v3);
ASSERT_TRUE(v1 != v4);

ASSERT_TRUE(v2 == v2);
ASSERT_TRUE(v2 != v3);
ASSERT_TRUE(v2 != v4);
ASSERT_TRUE(v2 == v1);

ASSERT_TRUE(v3 == v3);
ASSERT_TRUE(v3 != v4);
ASSERT_TRUE(v3 != v1);
ASSERT_TRUE(v3 != v2);

ASSERT_TRUE(v4 == v4);
ASSERT_TRUE(v4 != v1);
ASSERT_TRUE(v4 != v2);
ASSERT_TRUE(v4 != v3);

ASSERT_FALSE(v4 == v2);
// This is a compile-time test
EXPECT_TRUE(true);
}

} // namespace test_tagged_union5

0 comments on commit 99f3f50

Please sign in to comment.