2012-06-02 32 views
3

可能重複:
Why can templates only be implemented in the header file?
Undefined reference to function template when used with string (GCC)
C++ templates, undefined referenceC++未能聯動,不確定參考

我覺得我失去了一些東西連接一個C++項目。 我不確定問題出在頭文件中還是包含在內,所以我做了一個最小的代碼示例來演示它。

主模塊 minmain.cpp:

#include <stdio.h> 
#include <vector> 
#include <string> 
#include "nodemin.h" 

using namespace std; 

int main() 
{ 
    // Blist libs are included 
    Node<int>* ndNew = ndNew->Root(2); 

    return 0; 
} 

頭文件 nodemin.h:

#ifndef NODETEMP_H_ 
#define NODETEMP_H_ 

using namespace std; 

template<class T> 
class Node 
{ 
protected: 

    Node* m_ndFather; 
    vector<Node*> m_vecSons; 
    T m_Content; 

    Node(Node* ndFather, T Content); 

public: 

    // Creates a node to serve as a root 
     static Node<T>* Root(T RootTitle); 
}; 

#endif 

節點模塊 nodemin.cpp:

#include <iostream> 
#include <string.h> 
#include <vector> 
#include "nodemin.h" 

using namespace std; 

template <class T> 
Node<T>::Node(Node* ndFather, T Content) 
{ 
    this->m_ndFather = ndFather; 
    this->m_Content = Content; 
} 

template <class T> 
Node<T>* Node<T>::Root(T RootTitle) { return(new Node(0, RootTitle)); } 

編譯行:

#g++ -Wall -g mainmin.cpp nodemin.cpp 

輸出:

/tmp/ccMI0eNd.o: In function `main': 
/home/******/projects/.../src/Node/mainmin.cpp:11: undefined reference to`Node<int>::Root(int)' 
collect2: error: ld returned 1 exit status 

我試過編譯爲對象,但鏈接還是失敗了。

回答

0

添加template class Node<int>;到nodemin.cpp:

#include <iostream> 
#include <string.h> 
#include <vector> 
#include "nodemin.h" 

using namespace std; 

template <class T> 
Node<T>::Node(Node* ndFather, T Content) 
{ 
    this->m_ndFather = ndFather; 
    this->m_Content = Content; 
} 

template <class T> 
Node<T>* Node<T>::Root(T RootTitle) { return(new Node(0, RootTitle)); } 

template class Node<int>; 
+1

雖然這解決了*這個特殊*的問題,它只是掩蓋了普遍的問題。沒有任何關於它做什麼的解釋,我會*不推薦這個解決方案,並且一般來說我懷疑它確實適合OP。 –

+0

它的工作原理。所以問題實際上是試圖將非類'int'放到類模板中,猜測我可能會因爲使用太多純粹的OOP而責怪自己。所以,如果一個模板'T型'它將是完全通用的,並且也適合非類型類型,對嗎? –

+0

看看你的問題的評論鏈接。真的,問題是由於這樣的事實造成的,編譯器在處理nodemin.cpp時不會生成T = int的實現。此外,編譯器在處理minmain.cpp時不會生成實現(因爲它未在此文件中定義)。所以,編譯器根本沒有爲T = int生成實現,因爲這個鏈接器找不到它。在nodemin.cpp結尾處放置'template class Node '提示編譯器生成相應的實現。 – Ruben