【发布时间】:2013-01-25 17:39:38
【问题描述】:
可能重复:
Why can templates only be implemented in the header file?
我正在研究一个 Matrix 类,并且我有一个方法 SetMatrix,我用它来用标准 c++ 二维数组初始化数组。
template <int width, int height>
static void SetMatrix(Matrix& matrix, double array[][width]) {
if (matrix.height_ != height || matrix.width_ != width) {
fprintf(stderr, "Incorrect matrix size\n");
return;
}
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
matrix.matrix_[y][x] = array[y][x];
}
并且该方法运行良好,但是当我尝试将其从头文件移动到 .cpp 实现文件时,出现链接器错误。
矩阵.cpp:
template <int width, int height>
void Matrix::SetMatrix(Matrix& matrix, double array[][width]) {
if (matrix.height_ != height || matrix.width_ != width) {
fprintf(stderr, "Incorrect matrix size\n");
return;
}
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
matrix.matrix_[y][x] = array[y][x];
}
g++ 输出:
g++ -Wall -Wextra main.cpp Matrix.cpp -o matrix
/tmp/ccMkObBs.o: In function `main':
main.cpp:(.text+0x81): undefined reference to `void Matrix::SetMatrix<2, 3>(Matrix&, double (*) [2])'
collect2: error: ld returned 1 exit status
我想知道如何将它移动到 .cpp 文件中,或者我只是不走运,或者是否有更优雅的方式来做到这一点?我发现的大部分资源都是处理模板类的静态方法,而不是非模板类的静态模板方法。如果有帮助,这也是我的调用代码
int main() {
double input[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
Matrix matrix(2, 3);
Matrix::SetMatrix<2, 3>(matrix, input);
matrix.Print();
}
【问题讨论】:
标签: c++ templates static header