2012-12-22 99 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,你根本不需要包含警衛。