2010-06-09 56 views
0

當我嘗試編譯此:什麼導致這個模板相關的編譯錯誤?

#include <map> 
#include <string> 

template <class T> 
class ZUniquePool 
{    
     typedef std::map< int, T* > ZObjectMap; 
     ZObjectMap  m_objects; 
public: 
    T * Get(int id) 
    { 
     ZObjectMap::const_iterator it = m_objects.find(id); 
     if(it == m_objects.end()) 
     { 
      T * p = new T; 
      m_objects[ id ] = p; 
      return p; 
     } 
     return m_objects[ id ]; 
    } 
}; 

int main(int argc, char * args) 
{ 
    ZUniquePool<std::string> pool; 
    return 0; 
} 

我得到這個:

main.cpp: In member function ‘T* ZUniquePool<T>::Get(int)’: 
main.cpp:12: error: expected `;' before ‘it’ 
main.cpp:13: error: ‘it’ was not declared in this scope 

我在Mac OS X 使用GCC 4.2.1它工作在VS2008。

我想知道是否可能是這個問題的變化: Why doesn't this C++ template code compile? 但由於我的錯誤輸出只是部分相似,我的代碼在VS2008,我不知道。

任何人都可以闡明我做錯了什麼嗎?

回答

9

您需要typename

typename ZObjectMap::const_iterator it = m_objects.find(id) 

由於ZObjectMap類型是依賴於模板參數,編譯器不知道什麼ZObjectMap::const_iterator是(也可能是一個成員變量)。您需要使用typename來通知編譯器假定它是某種類型的。

+0

太棒了!您不僅解決了我的問題,而且還讓我意識到對編譯器處理模板的方式有着根本性的重要性。 非常感謝。 – Setien 2010-06-11 06:53:26

2

另外提一下,GCC 4.5.0給出了下面的輸出,這將有助於你解決這個問題:

main.cpp: In member function 'T* ZUniquePool<T>::Get(int)': 
main.cpp:12:7: error: need 'typename' before 'ZUniquePool<T>::ZObjectMap:: const_iterator' because 'ZUniquePool<T>::ZObjectMap' is a dependent scope 
main.cpp:12:34: error: expected ';' before 'it' 
main.cpp:13:11: error: 'it' was not declared in this scope 
main.cpp: At global scope: 
main.cpp:23:5: warning: second argument of 'int main(int, char*)' should be 'char **' 
+0

謝謝 - 我會記住將來的模板編譯錯誤(切換到GCC的更新版本)。 – Setien 2010-06-11 06:52:55

相關問題