我有一個名爲Component
的基類,其中有許多類派生自它。我希望每個類都有一個與它相關的整數(只要它們從0開始並且是連續的,哪個組件獲得什麼值並不重要)。我不知道如何直接做到這一點,所以在相同的文件中Component
我增加了以下內容:靜態變量將其值自己重置爲0顯然
template <typename T>
class ComponentIdentifier
{
public:
static unsigned int cid;
};
static unsigned int CIDCounter = 0;
template <typename T> unsigned int ComponentIdentifier<T> = CIDCounter++;
template <typename T> unsigned int ComponentID()
{
return ComponentIdentifier<T>::cid;
}
unsigned int ComponentCount(); // Defined in .cpp file, just returns CIDCounter
現在我測試的的ComponentID()函數,它似乎很好地工作。我試過ComponentID的每個組件類都返回一個不同的整數,就像我期望的那樣。然而,每當我打電話給ComponentCount時,我得到0.
例如,如果我有下面的代碼行:
std::cout << ComponentID<AAA>() << std::endl;
std::cout << ComponentID<BBB>() << std::endl;
std::cout << ComponentID<CCC>() << std::endl;
std::cout << ComponentCount() << std::endl;
那麼我的輸出是:
0
1
2
0
我懷疑發生的事情是,CIDCounter被設置爲0它用於設置CID各的之後再次組件,但我不確定,而且看起來很奇怪。有沒有辦法做我想做的或者我瘋了,這整個計劃註定要失敗?
謝謝,這是做到了。 – Alex 2010-12-15 09:20:33