从这个问题Storing C++ template function definitions in a .CPP file中迁移,我试图将一个模板类的代码分离到头文件和源文件中。然而,我失败了,但我希望有人能在这种情况下给予一些启示。请注意,与该问题的不同之处在于他有一个模板函数,而不是一个类。
file.h
template<typename T>
class A {
public:
A();
private:
T a;
};
file.cpp
#include "file.h"
template<typename T>
A::A() { a = 0; }
template<int> class A;
还有 main.cpp
#include "file.h"
int main() {
A<int> obj;
return 0;
}
以及错误信息:
../file.cpp:4:1: error: invalid use of template-name ‘A’ without an argument list A::A() { a = 0; }
^ In file included from ../file.cpp:1:0: ../file.h:1:10: error: template parameter ‘class T’ template<typename T>
^ ../file.cpp:6:21: error: redeclared here as ‘int <anonymous>’ template<int> class A;
^ make: *** [file.o] Error 1