2012-12-22 45 views
0

可能重复:
Why do I get “unresolved external symbol” errors when using templates?无法解析的外部与模板

我试图实现使用模板的通用队列。

我有下面的代码在我的头:

template<class Item> 
class Queue{ 
protected: 
    struct linked_list; 
    int size; 
public: 
    Queue(); 
    Queue(Item T); 
}; 

我有一个Queue.cpp:

template<class Item> 
Queue<Item>::Queue() 
{ 

} 
template<class Item> 
Queue<Item>::Queue(Item T) 
{ 

} 

但我每次编译的时候,我得到的,因为无法解析外部的连接错误。

我重新安装了VS2012两次(认为链接器坏了),但问题不断出现。

我读过使用模板时,函数实现在单独的文件中存在一些问题,但是我没有看到任何解决方案,除了将实现放在标题中。

有没有更优雅的方式来做到这一点?

+0

查看http://stackoverflow.com/questions/3749099 – aschepler

回答

2

模板不支持a definition is provided elsewhere and creates a reference (for the linker to resolve) to that definition

您需要使用the inclusion model,把所有Queue.cpp定义为Queue.h文件。或在Queue.h的底部

#include "Queue.cpp" 
+0

真的吗?通常,在处理标题时,我所做的只是创建一个标题和一个具有相同名称的源,并在源代码中包含标题,并且它工作得很好。 –

+1

但这是模板,它不同 – billz

0

模板声明必须包含在您的源代码中。如果要分割他们,一个我喜欢使用的方法是:

上queue.h的底部:

#define QUEUE_H_IMPL 
#include "queue_impl.h" 

和queue_impl.h后,我

//include guard of your choice, eg: 
#pragma once 

#ifndef QUEUE_H_IMPL 
#error Do not include queue_impl.h directly. Include queue.h instead. 
#endif 

//optional (beacuse I dont like keeping superfluous macro defs) 
#undef QUEUE_H_IMPL 

//code which was in queue.cpp goes here 

其实现在已经看过它,如果你#undef QUEUE_H_IMPL,你根本不需要包含警卫。