Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add operator== to TaggedUnion.hpp #280

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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_
67 changes: 67 additions & 0 deletions tests/json/test_tagged_union5.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>

#include <gtest/gtest.h>

namespace test_tagged_union5 {

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);
}

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

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

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