c++ - 源文件中的模板类

标签 c++ templates c++11 syntax compiler-errors

从这个问题中移出 Storing C++ template function definitions in a .CPP file ,我试图在头文件和源文件中分离模板类的代码。然而,我失败了,但我希望有人能对这种情况有所了解。请注意,与问题的不同之处在于他有一个模板化函数,而不是一个类。

文件.h

template<typename T>
class A {
public:
    A();
private:
    T a;
};

文件.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>;

关于c++ - 源文件中的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307374/

相关文章:

c++ - 初始化静态初始化的每个结构字符缓冲区的最佳方法?

c++ - 显式类模板实例化的链接

c++ - visual studio 2015 无法编译有效代码(标准函数错误?)

c++ - 类 std::vector 没有名为的成员

c++ - 对所有 USB 设备使用 RegisterDeviceNotification()

c++ - gets() 不接受输入

c++ - 为什么 "using namespace std;"被认为是不好的做法?

sql - Go 模板用于连接 slice 中的查询

c++ - 使用 Qt 线程和信号的缓冲区溢出

c++ - 如何使用 QDataStream 从文件中读取二进制数据?