2010-12-22 94 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.但我会避免它 - 它会导致更多的问题,而不是它的价值。