在源文件中的模板类

3

从这个问题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
1个回答

4

请按如下修改你的.cpp文件:

template<typename T>
A<T>::A() { a = 0; } // note the <T>

template class A<int>;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接