问题描述
我正在像这样使用TBB库:
// Concurrency.hpp
#include <tbb/spin_mutex.h>
#include <tbb/mutex.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>
// Restrict templates to work for only the specified set of types
template<class T,class O = T>
using IntegerOnly = std::enable_if_t<std::is_integral<T>::value,O>;
// An extra helper template
template<class Fn,class I>
static IntegerOnly<I,void> loop_(const tbb::blocked_range<I> &range,Fn &&fn)
{
for (I i = range.begin(); i < range.end(); ++i) fn(i);
}
// Calling TBB parallel-for by this template
template<class It,class Fn>
static void for_each(It from,It to,Fn &&fn,size_t granularity = 1)
{
tbb::parallel_for(tbb::blocked_range{from,to,granularity},// => Error happens at this line
[&fn,from](const auto &range) {
loop_(range,std::forward<Fn>(fn));
});
}
我收到此错误:
Concurrency.hpp:43:32:错误:使用类模板'blocked_range'需要模板参数 block_range.h:45:7:注意:模板在此处声明
解决方法
tbb::blocked_range
是一个类模板,并且您在构造class template argument deduction(CTAD)时会通过省略任何显式模板参数来尝试使用它。
但是,template<typename Value> class blocked_range { public: //! Type of a value /** Called a const_iterator for sake of algorithms that need to treat a blocked_range as an STL container. */ typedef Value const_iterator; // ... //! Construct range over half-open interval [begin,end),with the given grainsize. blocked_range( Value begin_,Value end_,size_type grainsize_=1 ) // ... // ... };
CTAD是C ++ 17的一项功能,因此,如果使用较早的语言版本进行编译,则需要为Value
类模板指定tbb::blocked_range
类型的模板参数。从上面可以看到,Value
类型应作为迭代器类型,特别是在调用站点传递给其构造函数from
和to
的前两个参数的类型。因此,您可以按以下方式修改代码段:
// Calling TBB parallel-for by this template
template<class It,class Fn>
static void for_each(It from,It to,Fn &&fn,size_t granularity = 1)
{
tbb::parallel_for(tbb::blocked_range<It>{from,to,granularity},[&fn,from](const auto &range) {
loop_(range,std::forward<Fn>(fn));
});
}
从您在评论中提到的内容来看,这可能是一个可移植性问题,在此之后您可能会遇到更多问题,并且可能要考虑查看项目的编译标志,以便了解是否可以而是使用C ++ 17进行编译。
,错误显示'blocked_range' requires template arguments
。
一种解决方案是添加一些模板参数。我不知道它们应该是什么,但是也许
tbb::blocked_range<I>{from,granularity}
^^^
template argument here