【问题标题】: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?GPU(Metal)上的C++类型,如何将另一个变量的类型保存到一个类中,并确保所有类实例具有相同的大小?
【发布时间】:2020-09-06 12:57:08
【问题描述】:

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.
}

可以使用enum 作为类型,然后在 GPU 上检查类型和分支。我已经让它在 GPU 上工作了。但是如果我可以将type 直接保存到这个类中,也许我可以在 GPU 上进行类型转换和使用模板。据我了解,它将减少所有丑陋的分支。

所有逻辑都发生在 GPU 端,CPU 端只是准备数据。 GPU(Metal) 没有超类和虚函数,但支持模板。除非我可以在 GPU 上获得相同的类型,否则最好避免使用任何 std 内容。

【问题讨论】:

  • 您在寻找虚函数吗?这个问题对我来说不是很清楚。
  • 看来您正在寻找一个歧视性工会。在现代 C++ 中,您可以使用 std::variant
  • 你能解释一下你到底想要完成什么吗?感觉就像一个 XY 问题,知道你在做什么可能有助于答案
  • Metal 不支持虚函数@StephenNewell
  • 是的,请澄清。我只是说你标记了模板。如果您想在BVH 中存储SphereSquare 的实例,您当然可以使用template <typename T> BVH { T instance; }(从问题中不太清楚,你说你想存储类型,但我想你想要存储对象)。然而BVH<Sphere>BVH<Square> 是两个完全不相关的类型,现在还不清楚你真正需要什么......

标签: c++ templates gpgpu metal


【解决方案1】:

由于您谈到解析到 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();
    }
}

有关unions 的更多信息,请参阅https://en.cppreference.com/w/cpp/language/union

但同样,unions 是丑陋的,我只在你真的必须这样做时才提到那些可能性,丑陋的非常低级的编程。如果您可以通过将BVH 制作为模板,或者如果您可以引入一些超类FigureSquareSphere 从中继承并让BVH 存储指向Figure 的指针,甚至可以使用@ 987654331@为子类提供覆盖的接口,这样会更好。

【讨论】:

  • 嗨,我已经在 GPU 上有了一个分支和类型检查版本。据我了解,我们的解决方案不同,但没有根本区别。我的目的是减少分支和检查。
  • @iaomw 的意思是,最后,你必须做一些事情来辨别你拥有哪种类型。即使在拥有超类的多态方法中,您也会隐含在查找表中,对吗?也就是说,在模板方法中,您可能至少会这样做,因为它是在构建时决定的。
  • @iaomw 无论如何,如果你想在 GPU 上进行超优化,我会采用几种方法并测量时间。如果时间没有那么不同,请选择最易读的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多