2010-12-22 93 views
3

我正在使用模板在C++中實現哈希表和鏈接列表(沒有STL - 不要問),而且我遇到了將它們與g ++鏈接起來的問題。如果我把所有的.cpp文件包括在一起,一切都可以正常工作,所以我的代碼肯定有效,這只是讓我絆倒的鏈接。使用g ++鏈接模板

我讀the bit in the GCC manual about template instantiation,但不知道如何應用它。

我的問題: 我有我的哈希表HashMap<T>HashEntry<T><T>是價值 - 我的鑰匙是std::string S)。我的鏈接列表有LinkedList<T>Node<T>(其中<T>是值)。

在我的哈希表,我有:

template <class T> class HashMap { 
    ... 
    private: 
     LinkedList< HashEntry<T> >** buckets; 
} 

這給了我的HashEntry<T>個鏈表。

在一個單獨的文件,我有我的鏈表類的聲明:

template <class T> 
    class Node { 
     ... 
     private: 
      T data; 
} 

template <class T> class LinkedList { 
    ... 
    private: 
    Node<T> * first; 
} 

然後,當我嘗試(與g++ -c -frepo *.cpp編譯後)鏈接的一切,我得到:

g++ -frepo -o app LinkedList.o HashMap.o 
[...unrelated errors about not having a main method - they go away when I link that in] 
HashMap.o: In function `HashMap<int>::~HashMap()': 
HashMap.cpp:(.text._ZN7HashMapIiED1Ev[HashMap<int>::~HashMap()]+0x65): undefined reference to `LinkedList<HashEntry<int> >::~LinkedList()' 
HashMap.o: In function `HashMap<int>::insert(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)': 
HashMap.cpp:(.text._ZN7HashMapIiE6insertESsi[HashMap<int>::insert(std::basic_string<char,  std::char_traits<char>, std::allocator<char> >, int)]+0xff): undefined reference to  `Node<HashEntry<int> >::setData(HashEntry<int>)' 

谷歌搜索在我看來,我的程序使用了顯式模板類型的建議。該方法適用於HashMapHashEntry(我加(template class HashMap<int>template class HashEntry<int>

然而,我無法弄清楚如何使這項工作爲LinkedListNode類,因爲模板實例是HashEntries<int>,但是,我可以't把它放到LinkedList.h文件中,因爲它是我的哈希表的#include d。我也無法得到一個高級/ extern聲明。

我敢肯定,有一些相當簡單的東西我失蹤使所有這些工作。任何提示?

+0

是否有你的`LinkedList`析構函數的定義在任何地方?或`節點<...> :: setData()`? – robert 2010-12-22 00:04:20

+0

也許不相關,但是有什麼理由不使用make,waf,SCons等。 – robert 2010-12-22 00:05:21

回答

3

如果你正在製作模板類,因此將它們放入.cpp文件並單獨編譯並不是一個好主意。正確的方法是將它們放在.h文件(聲明和定義)中,並將它們包含在需要它們的地方。

原因是模板實際上不會被編譯,除非它們的模板參數被定義。

(故意避開提export關鍵字)。

2

它看起來像你定義在LinkedList.cpp模板類成員。通常需要在.h文件中完全定義模板(不僅僅是聲明)。有關解決方法,請參閱storing C++ template functions in a .cpp file.但我會避免它 - 它會導致更多的問題,而不是它的價值。