簡體   English   中英

GPU(Metal)上的C++類型,如何將另一個變量的類型保存到一個類中,並確保所有類實例的大小相同?

[英]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?

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 上獲得相同的類型。

由於您談論解析到 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();
    }
}

有關union的更多信息,請參閱https://en.cppreference.com/w/cpp/language/union

但同樣, union是丑陋的,我只在你真的必須這樣做時才提到那些可能性,丑陋的非常低級的編程。 如果你可以讓BVH成為一個模板,或者如果你可以引入一些超類Figure從中SquareSphere繼承並讓BVH存儲一個指向Figure的指針,甚至可能Figure提供了一個接口供子類覆蓋,那將最好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM