Reputation: 611
In my function I want to check if calss is comparable and perform comparison only if it is:
template <typename T>
int compare(const T& a, const T& b)
{
if constexpr (std::three_way_comparable<T>) {
std::cerr << "comparable " << typeid(T).name() << "\n";
if (a == b) {
return 0;
}
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
} else {
std::cerr << "not comparable " << typeid(T).name() << "\n";
}
return 0;
}
This works fine for simple cases such as:
struct CompStruct
{
int a {};
std::string b;
auto operator<=>(const CompStruct&) const = default;
};
struct UncompStruct
{
int a {};
std::string b;
auto operator<=>(const UncompStruct&) const = delete;
};
CompStruct cs_a, cs_b;
compare(cs_a, cs_b); // prints "comparable""
UncompStruct ucs_a, ucs_b;
compare(ucs_a, ucs_b); // prints "not comparable"
But fail to compile when using nested boost::multiindex with something uncomaprable inside:
namespace bmi = boost::multi_index;
using MultiIndex = bmi::multi_index_container<
UncompStruct, bmi::indexed_by<bmi::random_access<>>>;
struct bad_type : std::map<std::string, MultiIndex>
{};
bad_type bt_a;
bad_type bt_b;
compare(bt_a, bt_b); // fails to compile
If I change UncompStruct
inside multiindex to CompStruct
it compiles fine.
Full code here: https://godbolt.org/z/s5f4E63hc
Question: Is there suggestion on how to check if class is really comparable.
Upvotes: 1
Views: 46