使用OpenMP时,我想为类模板声明一个用户定义的缩减(reduction)。
#include <omp.h>
#include <iostream>
template<typename T>
class Foo
{
public:
T Data_;
template<typename U> friend Foo<U> operator+( const Foo<U>& lhs, const Foo<U>& rhs );
};
template<typename U>
Foo<U> operator+( const Foo<U>& lhs, const Foo<U>& rhs )
{
Foo<U> Addition;
Addition.Data_ = lhs.Data_ + rhs.Data_;
return Addition;
}
#pragma omp declare reduction( + : template<typename U> Foo<U> : omp_out = omp_out + omp_in ) initializer (omp_priv=omp_orig)
int main( int argc, char* argv[] )
{
Foo<int> Array[100];
for ( int i = 0 ; i < 100 ; ++i )
{
Array[i].Data_ = i;
}
Foo<int> Sum {0};
#pragma omp parallel for num_threads(4) reduction( + : Sum )
for ( int i = 0 ; i < 100 ; ++i )
{
Sum.Data_ += Array[i].Data_;
}
std::cout << Sum.Data_ << std::endl;
return 0;
}
但我遇到了以下错误:
error: expected type-specifier before 'template'
#pragma omp declare reduction( + : template<typename U> Foo<U> : omp_out = omp_out + omp_in ) initializer (omp_priv=omp_orig)
^~~~~~~~
我可以通过将template<typename U> Foo<U>
替换为Foo<int>
来修复错误。
但是我想知道是否有保持使用template
的解决方案。
谢谢。
const vector<T>&
而不是vector<T>
来避免不必要的复制。 - Jérôme Richard