Templates 在推力中使用模板在执行策略之间切换
我有一个模板化的代码,在调用推力算法时,我想在cuda或omp执行策略之间进行选择。编译器似乎不会根据容器自动检测适当的策略。我认为在不使用if-else的情况下选择策略的一个正确方法是使用整数模板参数为推力的算法编写一个包装器。下面是一个示例,它提供了一个针对推力::transform的最小代码,但它不会编译。然而,一个类似的用于推力::for_的包装器编译起来没有任何问题。我错过了什么Templates 在推力中使用模板在执行策略之间切换,templates,cuda,thrust,Templates,Cuda,Thrust,我有一个模板化的代码,在调用推力算法时,我想在cuda或omp执行策略之间进行选择。编译器似乎不会根据容器自动检测适当的策略。我认为在不使用if-else的情况下选择策略的一个正确方法是使用整数模板参数为推力的算法编写一个包装器。下面是一个示例,它提供了一个针对推力::transform的最小代码,但它不会编译。然而,一个类似的用于推力::for_的包装器编译起来没有任何问题。我错过了什么 #include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include<thrust/transform.h>
#include<thrust/execution_policy.h>
#include<thrust/host_vector.h>
#include<thrust/device_vector.h>
#include <thrust/system/omp/execution_policy.h>
#include<iostream>
typedef thrust::device_vector<int> d_vec;
typedef thrust::host_vector<int> h_vec;
template<typename T>
struct myfunc{
__host__ __device__
T operator()(const T& i) const {
return T(2)*i;
}
};
template<int N, typename InputIter, typename OutputIter, typename Functor>
void transform(InputIter& begin1, InputIter& end1, OutputIter& begin2, Functor& func){
switch (N){
case 0:
thrust::transform(thrust::device, begin1, end1, begin2, func);
break;
case 1:
thrust::transform(thrust::omp::par, begin1, end1, begin2, func);
break;
}
}
int main(){
int n = 4;
thrust::counting_iterator<int> begin(0);
thrust::counting_iterator<int> end = begin+n;
d_vec device_vector(n);
h_vec host_vector(n);
transform<0>(begin, end, device_vector.begin(), myfunc<int>());
transform<1>(begin, end, host_vector.begin(), myfunc<int>());
}
修复方法是按值传递迭代器和函子。如果我们希望通过引用传递它们,我们必须声明它们没有使用关键字const进行修改,即 或
您可以发布编译错误消息吗?错误:没有与参数列表匹配的函数模板转换实例参数类型有:推力::计数迭代器、推力::计数迭代器、推力::细节::正常迭代器、myfunc
void transform(InputIter begin1, InputIter end1, OutputIter begin2, Functor func)
void transform(const InputIter& begin1, const InputIter& end1, const OutputIter& begin2, const Functor& func)