问题描述
我将一些物理仿真代码从C ++移植到CUDA。
I am porting some physics simulation code from C++ to CUDA.
基本算法可以理解为:向一个向量的每个元素应用一个算子。在伪代码中,模拟可能包括以下内核调用:
The fundamental algorithm can be understood as: applying an operator to each element of a vector. In pseudocode, a simulation might include the following kernel call:
apply(Operator o, Vector v){
...
}
例如:
apply(add_three_operator, some_vector)
在我的C ++代码中,我有一个抽象基类Operator,有许多不同的具体实现。重要的方法是
class Operator {
virtual double operations(double x)= 0;
操作符compo(操作符lo,操作符ro);
...
}
In my C++ code, I have an abstract base class Operator, with many different concrete implementations. The important method is class Operator{ virtual double operate(double x) =0; Operator compose(Operator lo, Operator ro); ... }
AddOperator的实现可能如下所示:
The implementation for AddOperator might look like this:
class AddOperator : public Operator{
private:
double to_add;
public:
AddOperator(double to_add): to_add(to_add){}
double operator(double x){
return x + to_add;
}
};
操作符类具有缩放和组成Operator的具体实现的方法。
The operator class has methods for scaling and composing concrete implementations of Operator. This abstraction allows me to simply compose "leaf" operators into more general transformations.
例如:
apply(compose(add_three_operator, square_operator), some_vector);
将向量的每个元素添加三个方形。
would add three then square each element of the vector.
问题是CUDA不支持内核中的虚拟方法调用。我当前的想法是使用模板。然后内核调用看起来像:
The problem is CUDA doesn't support virtual method calls in the kernel. My current thought is to use templates. Then kernel calls will look something like:
apply<Composition<AddOperator,SquareOperator>>
(compose(add_three_operator, square_operator), some_vector);
有任何建议吗?
推荐答案
这样的东西可能...
Something like this perhaps...
template <class Op1, class Op2>
class Composition {...}
template <class Op1, class Op2>
Composition<Op1, Op2> compose(Op1& op1, Op2& op2) {...}
template<class C>
void apply(C& c, VecType& vec){...}
这篇关于如何在CUDA中使用多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!