为何放在一个.cpp文件中可以,放在不同的文件却不可以

为什么放在一个.cpp文件中可以,放在不同的文件却不可以?
#include <iostream>

//#include "CSingleton.h"

using namespace std;

//CSingleton.h
template <typename T>
class CSingleton
{
public:
static T *Instance();

private:
CSingleton();  // 默认的构造函数
CSingleton(const CSingleton<T> &other);  // 拷贝构造函数
CSingleton &operator=(const CSingleton<T> &other);  // 赋值函数
~CSingleton();  // 析构函数

static T *m_ptInstance;
};

//CSingleton.cpp
template <typename T>
T *CSingleton<T>::m_ptInstance = NULL;

template <typename T>
T *CSingleton<T>::Instance()
{
if (NULL == m_ptInstance)
{
m_ptInstance = new T();
}

return m_ptInstance;
}

//main.cpp
/* 测试类 */
class CTest
{
public:
CTest()
{
cout<<"i: "<<i<<endl;
++i;
}

~CTest()
{
}

private:
static int i;
};

int CTest::i = 0;

int main(void)
{
CTest *pTest = CSingleton<CTest>::Instance();
CTest *pTest2 = CSingleton<CTest>::Instance();

getchar();
return 0;
}

为什么放在一个.cpp文件中可以,放在不同的文件却不可以?
------解决思路----------------------
模板不可分离编译
------解决思路----------------------
可以用.h .cpp分开写,但.h 末尾用#include "xx.cpp" 包含
------解决思路----------------------
多数编译器不支持模板分离编译。
放.h中好了。


------解决思路----------------------
模板不可分离编译
------解决思路----------------------
1.
 rename Singleton.cpp to Singleton.hpp

//Singleton.hpp
#include "Singleton.h"
.....

2. 
//test.h
#include "Singleton.h"
class CTest
{
public:
CTest()
{
cout<<"i: "<<i<<endl;
++i;
}

~CTest()
{
}

private:
static int i;
};
//prevent the automatic instantiation of members.
extern template  class Singleton<CTest>; 

/test.cpp
#inlcude "test.h"
#include "Singleton.hpp"

int CTest::i = 0;
template  class Singleton<CTest>; //Explicit Instantiation


3. in main.cpp or other src files that will use Singleton<CTest>

#include "CTest.h"


这样可加速编译, 只在CTest.cpp中实例化模板类Singleton<CTest>,main.cpp等用户只检查语法错误, 没有模板膨胀的问题.


------解决思路----------------------
extern template 已经在vs .net 2003中已经支持。
 

------解决思路----------------------
引用:
可以用.h .cpp分开写,但.h 末尾用#include "xx.cpp" 包含

野狐禅