繁体   English   中英

C ++重载std :: count_if()作为谓词和值

[英]C++ overloading std::count_if() for a predicate and a value

考虑下面的代码,其目的是重载std::count_if()以使用容器作为参数,而不是通常的输入和输出迭代器。

// overload for call with predicate
template<typename Cont_T, typename Pred_T>
typename std::iterator_traits<typename Cont_T::iterator>::difference_type 
count_if(const Cont_T& c, Pred_T p) {
    return std::count_if(c.begin(), c.end(), p);
}

// overload for call with value
template<typename Cont_T, typename T = typename Cont_T::value_type>
typename std::iterator_traits<typename Cont_T::iterator>::difference_type
count_if(const Cont_T& c, const T& val) {
    return std::count_if(c.begin(), c.end(), val);
}

int main() {
   using namespace std;

   vector<int> v{1,2,3};
   count_if(v, 2);          // ambiguous call

   return 0;
}

结果是编译器错误,表明调用不明确。

有没有办法使这项工作?

如果使用标准容器( value_type 1 ),则可以尝试:

// overload for call with predicate
template<typename Cont_T>
typename std::iterator_traits<typename Cont_T::iterator>::difference_type 
count_if(const Cont_T& c, std::function<bool(typename Cont_T::value_type)> p) {
    return std::count_if(c.begin(), c.end(), p);
}

// overload for call with value
template<typename Cont_T>
typename std::iterator_traits<typename Cont_T::iterator>::difference_type
count_if(const Cont_T& c, const typename Cont_T::value_type& val) {
    return std::count(c.begin(), c.end(), val);
}

通过强制第二个参数的类型(而不使其成为模板参数),可以避免歧义。 但是,我可能不会这样做,而是坚持使用count / count_if的标准版本。

1如果不能依赖Cont_T::value_type ,则可以用更“通用”的decltype(*c.begin()) )或类似的东西代替它。

有了SFINAE,您可以

namespace helper
{

    using std::begin;
    using std::end;

    struct low_priority {};
    struct high_priority : low_priority {};

    template<typename Cont, typename Pred>
    decltype(true == std::declval<Pred>()(*begin(std::declval<const Cont&>())),
             void(), std::size_t{})
    count_if(const Cont& c, Pred&& p, high_priority)
    {
        return std::count_if(begin(c), end(c), std::forward<Pred>(p));
    }

    template<typename Cont, typename T>
    decltype(*begin(std::declval<const Cont&>()) == std::declval<T>(),
             void(), std::size_t{})
    count_if(const Cont& c, T&& val, low_priority) {
        return std::count(begin(c), end(c), std::forward<T>(val));
    }

}

template <typename Cont, typename T>
std::size_t count_if(const Cont& c, T&& val_or_pred)
{
    return helper::count_if(c, std::forward<T>(val_or_pred), helper::high_priority{});
}

作为奖励,这也适用于C数组。

演示

两个错误:您混淆了std :: count()和std :: count_if(),并且使用错了。

首先,std :: count_if()需要谓词,而不是值。 谓词是一个函数(或lambda表达式),返回一个布尔值是否应计算参数。 您想输入一个值,因此需要使用std:count()代替。

其次,您不能仅传递向量。 相反,您需要传递由两个迭代器指定的范围。

请在此页面上查看std :: count()和std :: count_if()的工作示例: http ://en.cppreference.com/w/cpp/algorithm/count

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM