2012-09-29 42 views
0

可能重複:
Why can templates only be implemented in the header file?
What is an undefined reference/unresolved external symbol error and how do I fix it?在C在其他文件中聲明使用模板++

我已經在一個文件中定義的模板類。

point.h是

#ifndef POINT_H 
#define POINT_H 

using namespace std; 

template <typename T, int size> 
class point { 
private: 
    T coordinates[size]; 

public: 
    point(); 
    void set_coordinates(const T *); 
    void get_coordinates(T *); 
}; 

#endif /* POINT_H */ 

point.c是

#include "point.h" 

template <typename T, int size> 
point::point() { 
    for (int i = 0; i < size; i++) 
     coordinates[i] = 0; 
} 

template <typename T, int size> 
void point<T, size>::set_coordinates(const T *coordinates) { 
    for (int i = 0; i < size; i++) 
     this->coordinates[i] = coordinates[i]; 
} 

template <typename T, int size> 
void point<T, size>::get_coordinates(T *coordinates) { 
    for (int i = 0; i < size; i++) 
     coordinates[i] = this->coordinates[i]; 
} 

我使用這個模板爲point<int, 2> p0;。但編譯器給出錯誤,point<int, 2>未定義。 我搜索了這個,發現了兩個解決方案 - 1.使用export變量。但我讀過它並不支持所有的編譯器。所以,我不想使用它。 2.建立明確的階級特喜歡

template <> class point<int> { 
    ... 
} 

但不存在任何其他方式做到這一點? (我指的是C++標準集裝箱,他們可能使用了一些技術來做到這一點。)

+1

http://stackoverflow.com/a/12574417/673730 –

回答

1

的C的解決方案++標準容器是把一切都在頭文件。

1

你應該把所有屬於該模板point的定義(即,包括成員函數)的point.h文件,並將其包含在使用了point類,以便需要編譯器能夠實例化它的任何文件。詳情請參閱this question

C++編譯器和鏈接器有避免鏈接上出現「多重定義」錯誤的方法(標準狀態下的ODR規則必須如此)。