在源文件中模板化 class
Templated class in source file
从这个问题 Storing C++ template function definitions in a .CPP file 移开,我试图在头文件和源文件中分离模板化 class 的代码。然而,我失败了,但我希望有人能对这种情况有所了解。请注意,与问题的不同之处在于他有一个模板函数,而不是 class.
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
像这样修改您的 .cpp 文件:
template<typename T>
A<T>::A() { a = 0; } // note the <T>
template class A<int>;
从这个问题 Storing C++ template function definitions in a .CPP file 移开,我试图在头文件和源文件中分离模板化 class 的代码。然而,我失败了,但我希望有人能对这种情况有所了解。请注意,与问题的不同之处在于他有一个模板函数,而不是 class.
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
像这样修改您的 .cpp 文件:
template<typename T>
A<T>::A() { a = 0; } // note the <T>
template class A<int>;