簡體   English   中英

如何為全局類型提供 static 計數器?

[英]How to have a static counter for global types?

我想要一個 static 計數器,每次創建另一種類型 class 時都會遞增。 這是我嘗試過的:

template <typename Type>
class Sequential_ID_Dispenser
{public:
    static inline int nextDispensed = 0;
    static int getID() { return nextDispensed++; }
};

struct DummyTypeForComponentIDs {}; // So that the same type is passed to getID()

template <typename T>
struct Component { 
    static inline int componentTypeID = Sequential_ID_Dispenser<DummyTypeForComponentIDs>::getID();
    
    
};

// The reason I've made it inherit like this is so that any time I add a new Component type/struct it'll automatically get an ID for that type
struct Hat : Component<Hat> {};
struct Tie : Component<Tie> {};

int main()
{
    

    int id = Hat::componentTypeID; // = 0
    id = Tie::componentTypeID; // = 1
}

這行得通。 但我想選擇輕松地從任何其他組件繼承,但它不能像這樣工作,例如:

template <typename T>
    struct Component { 
        static inline int componentTypeID = Sequential_ID_Dispenser<DummyTypeForComponentIDs>::getID();
   };

    struct Hat : Component<Hat> {};
    struct Tie : Component<Tie> {};
    struct BlueHat : Hat {};

int main()
{
    int id = Hat::componentTypeID; // = 0
    id = Tie::componentTypeID; // = 1
    
    id = BlueHat::componentTypeID; // = 0, gets the same number as struct Hat : Component<Hat>{}
}

有沒有好的解決方案? 理想情況下,我想在不將 arguments 傳遞給基本構造函數的情況下定義任何新結構。 我意識到我為此使用了 CRTP,這正是我為使其工作所做的工作,但必須有更簡單的方法,對吧?

編輯:實際上我很驚訝解決方案並不容易,我想要的只是我在全局命名空間中創建的每個 class 以獲得新的 ID,我猜是編譯時間或運行時。

對於類型上的(運行時)計數器,您不需要 inheritance。

您甚至可以使用模板變量 (C++14):

std::size_t getId()
{
    static std::size_t counter = 0;
    return counter++;
}

template <typename T>
std::size_t Id = getId();

演示

我看不到一個簡單的方法來擴展你當前的解決方案來做到這一點,除非你想開始在每個 inheritance 聲明器上拋出virtual並且記住每次都這樣做

無論如何,“計數類型”似乎有點反模式。 我們已經有了唯一的類型標識符,通過typeid

如果您真的需要一個int ,您可以讓一些經理 class 接受std::type_info並為您提供該類型獨有的int ,可能使用 map 為其供電。 但是,如果您可以首先存儲std::type_info ,那就更好了。 缺點是這些信息不會靜態可用(即“在編譯時”)。

暫無
暫無

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

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