模板类怎么在另一个文件中使用?

//test.h
template
class A{
public:
A();
void fun();
};

//test.cpp
#include"test.h"
template
A::A(){}

template
void A::fun(){}

int main(){
A a;//在test.cpp里面可以编绎通过,但是在另一个文件里,我也#include"test.h"怎么就:undefined reference to `A::A()'?
}
//这个怎么办啊?
除了#include以外还有没有别的办法

来自:http://opencrazy.iteye.com/blog/365321

  1. 将C++模板类的声明和定义都放在一个文件,如.h或.cpp文件中 使用的时候加入#include "模板类文件名.h(或.cpp)“即可。
  2. 将C++模板类的声明和定义分别放在.h和.cpp文件中
    且在.cpp文件中包含 #include ".h"

    不过在使用时,会因为不同的开发环境而有所不同:
    a. 在集成开发环境code::blocks下
    在调用程序中只加入 #include "模板类.cpp" 可以编译、运行通过
    或者同时加入 #include "模板类.h" 和 "模板类.cpp" 也可以编译、运行通过
    但只加入 #include "模板类.h" 是不能够运行通过,会出现 undefined reference to 错误
    b. 在linux gcc 环境下:
    在调用程序中只能加入 #include "模板类.cpp" 才能编译、运行通过
    否则 如果同时加入 #include "模板类.h" 和 "模板类.cpp" 则出现 class 重复定义的错误

总结: 为什么需要在调用程序中加入 #include "模板类.cpp" 那是因为只有将模板类.cpp文件同调用程序.cpp文件放在一起编译、运行才能真正确定类的真正类型,才能运行通过,不出现link之类(undefined reference to)的错误

没有别的办法。模板类,最好连同实现都放到.h里头。

不用说了,楼上总结的很好了。