在cuda中使用静态成员函数模板结构的另一种方法
Alternative way to template struct with static member function in cuda?
在C++中,我经常使用封装在模板结构中的静态函数,以便能够在编译时指定函数模板,从而进行各种优化,例如内联等(顺便问一句,这有名字吗?)。示例(相当做作,可能有错误,但你明白了):
template <int dim>
struct ImplementationA {
static float compute(float a) {
// do stuff, e.g.
return 2*pow(a,dim);
}
};
template <int dim>
struct ImplementationB {
static float compute(float a) {
// do other stuff, e.g.
return 3*pow(a,dim);
}
};
template <template <int> class ImplT, int dim> class Test {
void compute_stuff(float *dst, const float *src, int N) {
for(int i=0; i<N; i++)
dst[i] = ImlT<dim>::compute(src[i]);
}
};
void main() {
float v1[100];
float v2[100];
Test<ImplementationB,3> t;
t.compute_stuff(v2,v1,N);
}
然而,如果我想在compute
作为内核的CUDA中做同样的事情,即__global__
,这是不可能的,因为不能有static __global__
成员函数。我还有什么其他的可能性可以提供同样最小的性能开销?我使用GCC 4.6,所以一些C++11功能不可用。
您可以创建一个在__device__
方法中实现的模板类和只使用该类并调用方法的小模板__global__
函数:
template <int dim> class ImplementationA
{
public:
// parameters
float *dst;
const float *src;
int N;
// implementation
__device__ void compute()
{
float a = src[threadIdx.x];
// ...
}
};
// The same for ImplementationB
// global function
template <class Impl>
__global__ void compute(Impl impl)
{
impl.compute();
}
// call
ImplementationA<3> impl;
impl.src = src;
compute<<<1, 32>>>(impl);
相关文章:
- 文本冒险游戏 - 如何区分一种项目类型与另一种项目类型以及如何构建项目类/子类
- 为什么一种算法在相同的时间复杂度下比另一种算法更快?
- 当 c++ 需要一种数据类型并获取另一种数据类型时会发生什么?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 只需要知道我在c ++中打印模式的方式是否有效,或者有另一种方法可以有效地做到这一点
- void* 数组将元素转换为另一种类型
- 在C++中使用另一种语言
- 将 X 坐标从一种分辨率转换为另一种分辨率
- 在 c++ 中将一种结构类型分配给另一种类型
- 如何在一种方法中创建对象并在另一种方法中使用它
- 常量静态成员函数:有另一种方法可用吗?
- 将空基类优化对象强制转换为另一种类型是否会破坏严格的别名?
- 错误将结构复制到同一类型的另一种
- 将指向结构的指针转换为具有较少字段数的另一种结构类型
- 在cuda中使用静态成员函数模板结构的另一种方法
- 将C++结构写入文件并使用另一种编程语言读取文件
- 当需要修改元素时,另一种类似集合的数据结构是什么?
- 你能把一个异常继承层次结构包装到另一个吗?——或者,另一种干净的处理方式
- 在数据结构中保存成员的另一种方法
- 引用结构中成员的另一种方法