Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a universal function for both sequence and associative container?

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

  1. Check if class C has member function const_iterator find(key_type) const for container classes like set/map.
  2. If it doesn't contain find(), then we use 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)

like image 481
yueq Avatar asked Dec 17 '22 11:12

yueq


1 Answers

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.

like image 68
康桓瑋 Avatar answered Mar 16 '23 00:03

康桓瑋