#pragma once
//type.h
#include "stdafx.h"
template<typename T>
class CType
{
protected:
// 存储的值
T m_Value;
public:
// 默认构造函数
CType(T m_initValue); // 获得值
T Get(void)
{
return m_Value;
}
T operator =(T v);
};#include "StdAfx.h"
#include "Type.h"
//type.cpp
template<typename T>
// 默认构造函数
CType<T>::CType(T m_initValue)
:m_Value(m_initValue)
{
} template<typename T>
T CType<T>::operator =(T v)
{
return m_Value=v;
}// Types.cpp : 定义控制台应用程序的入口点。
//#include "stdafx.h"
#include "Type.h"
using namespace std;
template<typename T>
istream& operator >>(istream& input,CType<T> type)
{
T tmp;
input >> tmp;
type=tmp;
return input;
}
template <typename T>
ostream& operator<<(ostream &output,CType<T> type)
{
output << type.Get();
return output;
}int _tmain(int argc, _TCHAR* argv[])
{
typedef CType<int> TINT;
TINT a(0),b(0),c(0),d(0);
cin >> a >> b;
c=a;
d=b;
cout << c << " " << d << endl;
return 0;
}
Types.obj : error LNK2001: 无法解析的外部符号 "public: __thiscall CType<int>::CType<int>(int)" (??0?$CType@H@@QAE@H@Z)
1>Types.obj : error LNK2001: 无法解析的外部符号 "public: int __thiscall CType<int>::operator=(int)" (??4?$CType@H@@QAEHH@Z)
1>D:\My Documents\Visual Studio 2010\Projects\vc2010\Types\Types\Debug\Types.exe : fatal error LNK1120: 2 个无法解析的外部命令
比如:#include "stdafx.h"#include <iostream>
using namespace std;template<typename T>
class CType
{
protected:
// 存储的值
T m_Value;
public:
// 默认构造函数
CType(T m_initValue); // 获得值
T Get(void)
{
return m_Value;
}
T operator =(T v);
};//type.cpp
template<typename T>
// 默认构造函数
CType<T>::CType(T m_initValue)
:m_Value(m_initValue)
{
}template<typename T>
T CType<T>::operator =(T v)
{
return m_Value=v;
}// Types.cpp : 定义控制台应用程序的入口点。template<typename T>
istream& operator >>(istream& input,CType<T> type)
{
T tmp;
input >> tmp;
type=tmp;
return input;
}
template <typename T>
ostream& operator<<(ostream &output,CType<T> type)
{
output << type.Get();
return output;
}int _tmain(int argc, _TCHAR* argv[])
{
typedef CType<int> TINT;
TINT a(0),b(0),c(0),d(0);
cin >> a >> b;
c=a;
d=b;
cout << c << " " << d << endl;
return 0;
}
#include "Type.cpp"即可
#include "Type.cpp"
#include "Type.h"
如果模板类的声明和定义分别放在头文件和源文件中。当实例化的时候,只包含头文件会发证链接错误。
原因是模板类的实例化要分成两个步骤,模板的特例化和特例的实力化。
编译器在编译阶段,由于没有定义,所以编译器不能生成具体的模板特例,但是这并不会报错误,编译器将
把问题抛给链接器来做。在编译源文件的时候,程序找不到该模板的特例,只是有模板而已,所以无法生成
对象。所以会发生错误。
解决办法,按主流编译器的做法,把声明和定义都放在头文件中
#ifndef Compiled
#define Compiled
#include <iostream>using namespace std;class Catideology
{
private:
string m_sql;
const string m_model;public:
Catideology(string sql);
int ParseSql();
};template<typename T>
class CType
{
protected:
// 存储的值
T m_Value;
public:
// 默认构造函数
CType(T m_initValue); // 获得值
T Get(void)
{
return m_Value;
}
T operator =(T v);
};#endif
然后去掉type.cpp 文件,按现在的方法编译就ok
#ifndef Compiled
#define Compiled
#include <iostream>template<typename T>
class CType
{
protected:
// 存储的值
T m_Value;
public:
// 默认构造函数
CType(T m_initValue)
:m_Value(m_initValue)
{
}
// 获得值
T Get(void)
{
return m_Value;
}
T operator=(T v)
{
return m_Value=v;
}
};#endif