Sky Watch

C++ 类模板和多文件编译

By mw @

才知道原来在多文件编译时 c++ 类模板的声明和定义一定包含在同一个文件里。

以前写 Game of Life 的时候写了一个动态二维数组的模板,当时的文件是这样包含的:

// matrix.hpp template<class T> class TMatrix { // Declarations... };

#include "matrix.cpp" // Definitions

今天又用到了这个类,看这个文件包含不爽,改成了常规的

// matrix.hpp

template<class T> class TMatrix { // Declarations... };

// matrix.cpp

#include "matrix.cpp"

... // Definitions

然后在主程序里引用了一个成员函数

// main.cpp #include "matrix.hpp"

int main() { TMatrix<int> Matrix; Matrix.row(); return 0; }

编译:g++ -g main.cpp matrix.cpp

呜呼!出错了!说 TMatrix<int>::row() 只是声明了,没有定义。把 matrix 里的文件包含改成原来那个样子,然后只编译 main.cpp 就没问题了。百思不得其解,后来在 CSDN 上找到了这个。理论上,只要在模板声明前加上 export 关键字,然后用常规的多文件编译方法就可以,但是目前大部分编译器都不支持这个关键字。g++ 说“目前尚未实现,忽略”,真够直接的...