I'm trying to create a templated function contains that works for any container by trying these two steps:
- Using the container's own find method
.find(value)if it exists (which should be optimized for that specific container) - Using
std::find(xs.cbegin(), xs.cend(), v)as a fallback
It seems that boost::hana provides an is_valid or a sfinae function to check for that, but I wasn't able to figure out how they work...
template<typename TContainer, typename T>
bool
contains(
const T &v,
const TContainer &container)
{
constexpr auto has_find = boost::hana::is_valid([](auto &&xs, auto &&x) -> decltype((void)xs.find(x)) {});
if constexpr(has_find) {
return container.find(v) != container.cend();
} else {
return std::find(container.cbegin(), container.cend(), v) != container.cend();
}
}