c++ - 传递 std::plus<>() 作为谓词

标签 c++ c++11 stl

我需要通过std::plus<>()作为执行类似累加操作的函数的谓词,但我不太确定如何完成此操作。我想传递的模板参数 std::plus变为:

Pred && op

当我尝试使用 std::plus 作为 op 时:

return detail::reduce(..., std::plus<>()); //.... op = std::plus<>()

但这不起作用,我收到错误 error C2976: 'std::plus' : too few template arguments我应该看到它的到来,但我不知道如何解决这个问题并正确地传递加号。

我使用 op 的一个上下文:

std::accumulate(first, last, std::forward<T>(init),
                        std::forward<Pred>(op)));

detail::reduce 的一个这样的过载:

template <typename ExPolicy, typename InIter, typename T, typename Pred>
typename detail::algorithm_result<ExPolicy, T>::type
reduce_seq(ExPolicy const&, InIter first, InIter last, T && init,
    Pred && op)
{
    try {
        return detail::algorithm_result<ExPolicy, T>::get(
            std::accumulate(first, last, std::forward<T>(init),
                std::forward<Pred>(op)));
    }
    catch(std::bad_alloc const& e) {
        boost::throw_exception(e);
    }
    catch (...) {
        boost::throw_exception(
            hpx::exception_list(boost::current_exception())
        );
    }
}

最佳答案

如果要将谓词指定为函数参数,则必须为 std::plus 提供类型,如下上下文所示:

some_function(std::plus<T>());

但是您可以直接将其设为模板参数:如下所示:

template < template < class > class PRED, class T >
T foo(T a,T b)
{
    return PRED<T>()(a,b);
}
int main()
{
    int a = 1;
    int b = 1;
    foo<std::plus>(a,b);
    return 0;
}

对于你的情况,我认为这会起作用:

template <template <typename> typename Pred, typename ExPolicy, typename InIter, typename T >
typename detail::algorithm_result<ExPolicy, T>::type reduce_seq(ExPolicy const&, InIter first, InIter last, T && init)
{
   stuff = Pred<T>()(some_value,other_value);
}

//usage:
reduce_seq<std::plus>(arguments...);

关于c++ - 传递 std::plus<>() 作为谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24084471/

相关文章:

c++ - x&&y||z 是如何计算的?

c++ - 关于在循环中使用 ifstream 的错误

c++ - 简化这个表达式

c++ - 第三方库调用中的应用程序卡住

c++ - 模板函数参数类型中的模板标识符与 decltype

c++ - 使用 STL 与自定义实用程序类的程序员生产力

c++ - 在 C++ 中加速双绝对值

c++ - 改变这个指针指向的值

c++ - 将数组分成两组?

c++ - 为什么我的对象在 list::push_back() 之后会发生变化