mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-02 16:16:19 +08:00
Add operator== to TaggedUnion.hpp (#280)
Co-authored-by: Matthieu Dubuget <matthieu.dubuget@tpac-ndt.com>
This commit is contained in:
co-authored by
Matthieu Dubuget
parent
dda27f990c
commit
99f3f50fd3
@@ -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_
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user