可能重复:
为什么模板只能在头文件中实现?
你好.我在c ++中有一个愚蠢的程序,它包含一个头文件,其中一个类使用模板,一个cpp文件包含方法实现.
这是标题:
namespace SynQueueing {
template < class T, unsigned long SIZE = 0 >
class CommQueue {
public:
CommQueue();
~CommQueue();
}
}
Run Code Online (Sandbox Code Playgroud)
这是cpp
#include "myheader.h"
using namespace SynQueueing;
/* Default constructor */
template < class T, unsigned long SIZE >
CommQueue<T, SIZE>::CommQueue() {
}
/* Default destructor */
template < class T, unsigned long SIZE >
CommQueue<T, SIZE>::~CommQueue() {
}
Run Code Online (Sandbox Code Playgroud)
在主要内容中,我只需创建一个CommQueue对象
CommQueue cq;
当然包括CommQueue.h在cpp主文件中.
嗯,编译器疯了告诉我这个:
/tmp/ccvJL8VI.o:在函数`main'中:
entry.cpp :(.text + 0x2c):未定义引用`SynQueueing :: CommQueue :: CommQueue()'
entry.cpp :(.text + 0x10e):未定义引用`SynQueueing :: CommQueue :: ~CommQueue()'
entry.cpp :(.text + 0x135):未定义引用`SynQueueing :: CommQueue :: ~CommQueue()'
collect2:ld返回1退出状态
entry.cpp是main所在的文件.任何的想法?
谢谢
对于模板,您通常必须将实现放在.h/.hpp文件中.这可能看起来不自然,但将模板视为一些特殊的"宏",一旦您提供实际类型或值(在您的情况下,类型T和值SIZE),编译器就会扩展.由于大多数编译器都是实现的(在您的情况下是GCC),编译器必须在编译时找到要插入的代码,并且它会看到您定义的模板的实例化.