A step by step walkthrough for implementing a trait that models equality comparability for various types.
#include <catch2/catch_test_macros.hpp>
#include <string>
namespace lib_2f {
TRAIT(equal_comparable, anyxx::dynamic_copyable,
(OP_FREE(bool, ==, eq, (anyxx::self const&), const),
OP_IMPL(
public, bool, !=, ne, (anyxx::self const&), const,
(auto const& r) { return !Map{}.eq(self, r); })))
static_assert(is_equal_comparable_model<int>);
static_assert(is_equal_comparable_model<double>);
static_assert(is_equal_comparable_model<bool>);
static_assert(is_equal_comparable_model<std::string>);
template <anyxx::is_proxy Proxy>
void test_equal_comparable_(anyxx::any_<Proxy, equal_comparable> const& a,
anyxx::any_<Proxy, equal_comparable> const& b) {
CHECK((a == b) == (b == a));
CHECK((a != b) == (b != a));
CHECK((a == b) != (b != a));
CHECK((a != b) != (b == a));
}
template <is_equal_comparable_model T>
void test_equal_comparable(T const& a, T const& b) {
using namespace anyxx;
test_equal_comparable_<using_cref<T>>(a, b);
}
}
namespace app_2f {
struct a_type {
std::string name;
};
static_assert(!lib_2f::is_equal_comparable_model<app_2f::a_type>);
}
namespace app_2f {
struct b_type {
std::string name;
};
}
TRAIT_MAP(lib_2f::equal_comparable, app_2f::b_type) {
static auto eq(app_2f::b_type const& self, app_2f::b_type const& r) {
return self.name == r.name;
};
};
static_assert(lib_2f::is_equal_comparable_model<app_2f::b_type>);
TEST_CASE("equal_comparable static") {
lib_2f::test_equal_comparable(1, 1);
lib_2f::test_equal_comparable(app_2f::b_type{"A"}, app_2f::b_type{"B"});
}
TEST_CASE("equal_comparable dynamic") {
using namespace anyxx;
using namespace lib_2f;
std::vector<
std::pair<any_<val<>, equal_comparable>, any_<val<>, equal_comparable>>>
v{
{app_2f::b_type{"A"}, app_2f::b_type{"A"}},
{app_2f::b_type{"A"}, app_2f::b_type{"B"}},
{3, 3},
{3, 4},
{3.14, 3.14},
{3.14, 2.71},
{"hello", "hello"},
{"hello", "world"},
};
for (auto const& [a, b] : v) {
lib_2f::test_equal_comparable_(a, b);
}
{
using namespace anyxx;
using namespace lib_2f;
any<equal_comparable> a{42};
any<equal_comparable> b{3.14};
CHECK_THROWS_AS(a == b, type_mismatch_error);
}
}
C++ header only library for external polymorphism.