可能重复:
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++标准集装箱,他们可能使用了一些技术来做到这一点。)
http://stackoverflow.com/a/12574417/673730 –