2012-06-24 29 views
0

類型考慮以下方法C++特異於TYPE_INFO

static ComponentType & getTypeFor(const type_info &t){ 
     ComponentType * type = componentTypes[t.hash_code()]; 

     if(type == NULL) 
     { 
      type = new ComponentType(); 
      componentTypes[t.hash_code()] = type; 
     } 
     return *type; 
}; 

static bitset<BITSIZE> getBit(const type_info &t){ 
    ComponentType & type = getTypeFor(t); 
    return type.getBit(); 
} 

我稱這個如下

ComponentManagerType::getBit(typeid(MyComponentClass)); 
// Not an instance, passing class name 

現在作爲ComponentManagerType建議;這僅適用於組件。目前的問題是任何類型都可以通過。它不會造成任何傷害,但是會爲非組件對象創建id和bitset。

問: 如何強制此方法僅接受基本類型Component的對象?

我知道沒有直接的辦法。但是我非常在意這點。

編輯: 添加我自己的解決方案。不知道它是否猶太教。

+0

是不是可以用boost:is_base_Of? – GL770

+2

看起來您想使用模板。除非你有非常明確的理由,否則選擇RTTI而不是C++中的其他解決方案是不理想的。 – kennytm

+0

GL770截至目前,我對boost沒有興趣。@ kennyTM我想了很多。 – Sidar

回答

2

沒有直接的辦法; type_info是通過設計一個最小的接口。

我建議你改寫getBit作爲模板函數,可調用getBit<MyComponentClass>()。然後,您可以檢查模板中的基本類型(例如,使用boost::is_base_of;甚至可以使用std::enable_if強制執行模板函數聲明中的要求),並知道基類是否正確,然後執行typeid操作。

+0

我正在嘗試類似的東西。無法使其工作。我再試謝謝。 – Sidar

+0

@Sidar下面是一個例子:http://ideone.com/sYl1D(儘管我猜libstdC++在hash_code的使用方面存在一些問題,否則它會起作用)。此外,鏗鏘會給這個有用的筆記與此代碼的錯誤消息:「注:候選人模板被忽略:禁用'enable_if'[與T = NonComponent]」 – bames53

+0

是我自己想出來的,但你的例子看起來不錯。截至目前,我正在檢查我的typename/class是否是我的組件的基類。我謹記你的想法。 – Sidar

0

你說得對。任何派生物都可以通過。 C++語言不具備這種類型限制的功能。您只能使該方法爲protected/private來縮小可能呼叫地點的範圍。在較小的範圍內,您有更好的機會控制呼叫。

0
template<typename component> 
static bitset<BITSIZE> getBit(){ 

    //Check if we are being legal with components and shizzle 
    Component * c = (component*)0; 

    ComponentType & type = getTypeFor(typeid(component)); 
    return type.getBit(); 
} 

這會引發致命錯誤。 如果鑄件不起作用。它只是意味着它不是一個組件。

不知道這將如何公平,但。

但這似乎工作!