I am thinking to write a function that works both for sequence and associative container. That's something like
 template<class C, class V = typename C::key_type>
 bool has_val(const C& c, const V& v)`
Inside the function, I would like to
const_iterator find(key_type) const for container classes like set/map.std::find() for sequence container like std::vector.What's the best practice to check, (1)?
If what I described above is not the best, please advise if there's a better approach?
(Unfortunately I don't have access to newer Folly with macro FOLLY_create_member_invoker but I do have FOLLY_CREATE_HAS_MEMBER_FN_TRAITS. I couldn't successfully get it through, though)
Use SFINAE to detect whether to use c.find():
#include <algorithm>
template <class C, class V, typename = void>
constexpr inline bool use_mem_find = false;
template <class C, class V>
constexpr inline bool use_mem_find<C, V,
  std::void_t<decltype(std::declval<const C&>().find(std::declval<const V&>()))>> = true;
template<class C, class V> 
bool has_val(const C& c, const V& v) {
  auto end = std::end(c);
  if constexpr (use_mem_find<C, V>)
    return c.find(v) != end;
  else
    return std::find(std::begin(c), end, v) != end;
}
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With