我需要通过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/