c++ - 选择正确功能的更好方法?

标签 c++ c++14

我正在编写一个 contains() 实用程序函数,并想出了这个。我的问题是:有没有更好的方法来选择正确的函数来处理调用?

template <class Container>
inline auto contains(Container const& c,
  typename Container::key_type const& key, int) noexcept(
    noexcept(c.end(), c.find(key))) ->
  decltype(c.find(key), true)
{
  return c.end() != c.find(key);
}

template <class Container>
inline auto contains(Container const& c,
  typename Container::value_type const& key, long) noexcept(
    noexcept(c.end(), ::std::find(c.begin(), c.end(), key))
)
{
  auto const cend(c.cend());

  return cend != ::std::find(c.cbegin(), cend, key);
}

template <class Container, typename T>
inline auto contains(Container const& c, T const& key) noexcept(
  noexcept(contains(c, key, 0))
)
{
  return contains(c, key, 0);
}

最佳答案

作为记录,您可以这样写:

#include "magic.h"

template <typename T, typename... Us>
using has_find = decltype(std::declval<T>().find(std::declval<Us>()...));

template <class Container, typename T>
auto contains(const Container& c, const T& key)
{
    return static_if<detect<has_find, decltype(c), decltype(key)>{}>
    (
        [&] (auto& cont) { return cont.end() != cont.find(key); },
        [&] (auto& cont) { return cont.end() != std::find(cont.begin(), cont.end(), key); }
    )(c);
}

其中 magic.h 包含:

#include <type_traits>

template <bool> struct tag {};

template <typename T, typename F>
auto static_if(tag<true>, T t, F f) { return t; }

template <typename T, typename F>
auto static_if(tag<false>, T t, F f) { return f; }

template <bool B, typename T, typename F>
auto static_if(T t, F f) { return static_if(tag<B>{}, t, f); }

template <bool B, typename T>
auto static_if(T t) { return static_if(tag<B>{}, t, [](auto&&...){}); }

template <typename...>
using void_t = void;

template <typename AlwaysVoid, template <typename...> class Operation, typename... Args>
struct detect_impl : std::false_type {};

template <template <typename...> class Operation, typename... Args>
struct detect_impl<void_t<Operation<Args...>>, Operation, Args...> : std::true_type {};

template <template <typename...> class Operation, typename... Args>
using detect = detect_impl<void, Operation, Args...>;

DEMO

关于c++ - 选择正确功能的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484062/

相关文章:

c++ - 如何避免#include 对外部库的依赖

c++ - Visual C++ 2010 Express 中的默认 C++0x 模式是什么?

c++ - 强制编译器选择以 const T& 作为参数的复制构造函数

c++ - 在 constexpr 函数中改变 int

c++ - initializer_list 不可变的性质导致过度复制

c++ - 使用 ifstream 和 ofstream 与 cin 和 cout 的区别

c++ - Lemon Graph Library C++ 在节点中添加坐标

c++ - 将 QLineEdit 设置为仅接受数字

c++ - 如何从 std::async 任务返回 std::tuple

c++ - union 中的字符串、段错误