g++不支持模板类的分离编译,因此模板的实现最好都些在.h文件中,否则将出现undefined reference to XXXX 的错误。下面是一个出错的例子,解决方法就是将stack.cc中的代码移到stack.h中。
01
02
03 #ifndef __MY_STACK__
04 #define __MY_STACK__
05
06 #include <vector>
07 #include <stdexcept>
08
09 template <typename T>
10 class Stack {
11 public:
12
13
14
15
16
17
18 private:
19
20 };
21
22 #endif
23
24
25
26 #include "stack.h"
27
28 template <typename T>
29 void Stack<T>::push (T const& elem)
30 {
31
32 }
33
34 template <typename T>
35 void Stack<T>::pop ()
36 {
37
38
39
40
41 }
42
43 template <typename T>
44 T Stack<T>::top () const
45 {
46
47
48
49
50 }
51
52
53
54 #include <iostream>
55 #include "stack.h"
56
57 int main(void)
58 {
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 }