源文件中的模板化类

Templated class in source file

本文关键字:源文件      更新时间:2023-10-16

从这个问题移动到。cpp文件中存储c++模板函数定义,我试图在头文件和源文件中分离模板化类的代码。然而,我失败了,但我希望有人能对这种情况有所启发。注意,问题的不同之处在于,他有一个模板化的函数,而不是一个类。

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>;