如何实现序列容器和关联容器的通用功能?

yue*_*ueq 4 c++ templates std function-templates c++17

我正在考虑编写一个既适用于序列容器又适用于关联容器的函数。这就像

 template<class C, class V = typename C::key_type>
 bool has_val(const C& c, const V& v)`
Run Code Online (Sandbox Code Playgroud)

在函数内部,我想

  1. 检查 C 类是否具有 set/map 等容器类的成员函数const_iterator find(key_type) const
  2. 如果它不包含 find(),那么我们使用std::find()像 之类的序列容器std::vector

检查的最佳做法是什么(1)?

如果我上面描述的不是最好的,请告知是否有更好的方法?

(不幸的是,我无法使用宏访问较新的 Folly FOLLY_create_member_invoker,但我确实有FOLLY_CREATE_HAS_MEMBER_FN_TRAITS。不过,我无法成功完成它)

康桓瑋*_*康桓瑋 7

使用SFINAE检测是否使用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;
}
Run Code Online (Sandbox Code Playgroud)

演示。