[英]C++ type on GPU(Metal), how to save the type of another variable into a class, and make sure all the class instance have the same size?
Pseudocode on CPU side: CPU端的伪代码:
class Sphere {
//some property
}
class Square {
//some property
}
class BVH {
Type type; // save the type of Sphere or Square, or other types.
// But the instance of this class should maintain the same size.
}
It's possible using enum
as type, then checking type and branching on GPU.可以使用
enum
作为类型,然后在 GPU 上检查类型和分支。 I already got it working on GPU.我已经让它在 GPU 上工作了。 But if I can save the
type
directly into this class, maybe I can do type cast and use template on GPU.但是如果我可以将
type
直接保存到这个类中,也许我可以在 GPU 上进行类型转换和使用模板。 In my understanding, it will reduce all the ugly branching.在我的理解中,它会减少所有丑陋的分支。
All the logic happens on GPU side, CPU side is only preparing data.所有逻辑都发生在 GPU 端,CPU 端只准备数据。 GPU(Metal) doesn't super class and virtual function, but template is supported.
GPU(Metal) 没有超类和虚函数,但支持模板。 It's better to avoid any std stuff unless I can get the same type on GPU.
最好避免任何标准的东西,除非我可以在 GPU 上获得相同的类型。
Since you talk about parsing to a GPU, I assume that what you need can be an ugly solution, and your focus is on it being efficient rather than readable and nice.This would look something like this:由于您谈论解析到 GPU,我假设您需要的可能是一个丑陋的解决方案,您的重点是它的效率而不是可读性和美观性。这看起来像这样:
union Figure
{
Square square;
Sphere sphere;
};
class BVH {
public:
enum class FigureType { Square, Sphere };
BVH(Square square) // or const Square& square, or move...
{
type = FigureType::Square;
figure.square = square;
}
BVH(Sphere sphere) { ... }
// Or instead of the two signatures above,
// BVH(Figure figure, FigureType type);
// although that would allow the two parameters to not match.
// One might even consider to make the enum private.
void process()
{
// or switch
if(type == FigureType::Square) process_square();
...
}
private:
FigureType type;
Figure figure;
void process_square()
{
figure.square.do_something();
}
}
For more about union
s, see https://en.cppreference.com/w/cpp/language/union有关
union
的更多信息,请参阅https://en.cppreference.com/w/cpp/language/union
But again, union
s are ugly, and I only mention those as possibility when you really have to do it, ugly very low level programming.但同样,
union
是丑陋的,我只在你真的必须这样做时才提到那些可能性,丑陋的非常低级的编程。 If you can go by making BVH
a template, or if you can introduce some super class Figure
from which Square
and Sphere
inherit and have BVH
store a pointer to Figure
, maybe even with Figure
providing an interface for the sub classes to overwrite, that would be preferable.如果你可以让
BVH
成为一个模板,或者如果你可以引入一些超类Figure
从中Square
和Sphere
继承并让BVH
存储一个指向Figure
的指针,甚至可能Figure
提供了一个接口供子类覆盖,那将最好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.