-
类模板的声明与实现
C++模板类是不能定义在源文件的。
1.这是不允许的,因为模板类的成员函数的定义,是一种不完整的定义.
2.由于编译器不知道模板参数的具体类型,无法为其成员函数生成代码.
3.编译器在成员函数的调用处,才最终知道如何生成代码.
总之,模板类的成员函数的定义不能像普通类的成员函数一样,定义在源代码中,而只能定义在头文件中.
一下例子将会出现错误:
//文件Compare.h
#ifndef _COMPARE_H
#define _COMPARE_H
template
class Compare
{
public:
~Compare(void);
Compare(T,T);
T max();
T min();
private:
T x;
T y;
};
#endif
//文件Compare.cpp
#include"Compare.h"
template
Compare::Compare(T a,T b)
{
x=a;
y=b;
}
template
Compare::~Compare(void)
{
}
template
T Compare::max()
{
return (x>y)?x:y;
}
template
T Compare::min()
{
return (x>y)?y:x;
}
//文件main.cpp
#include
using namespace std;
#include"Compare.h"
int main()
{
Compare tt(1,2);
cout<<tt.max()<<endl;
system(“pause”);
getchar();
return 0;
}
这样做是会报错的哟~ -
模板嵌套(即模板里面再定义模板,实现的时候具体的写法)!
类模板的嵌套调用:前几天写binary tree的时候,有一个现象百思不得解,就是在模板类里面定义了模板函数,那这个函数在实现的时候时怎么样的呢?
template
class Myclass
{
public:
T a;
template <typename type_1 , typename type_2>
type_1 add(const type_1 lva ,const type_2 rva);
};
上述的模板类,里面嵌套定义了模板函数,怎么去实现呢?
template
template <typename type_1,typename type_2>//这里时我当时疑惑的地方
type_1 Myclass::add(const type_1 lva, const type_2 rva)
{
a = lva + rva;
return a;
}
当时自己写的方式为template<class T ,typename type_1, typename type_2>,这显然没有理解模板参数的定义,模板参数定义后,其作用域范围是接下来的类或者函数。然后模板可以嵌套定义。
再来一个更复杂的例子:
template
class Myclass
{
public:
T a;
template <typename type_1 , typename type_2>
type_1 add(const type_1 lva ,const type_2 rva);
template <class type_3>
class Myclass_2; // 声明放在这里,具体定义放在类外进行。
Myclass_2<T> C; // 定义一个Myclass_2 类 A。使用 T 进行实例化
};
template
template <typename type_1,typename type_2>
type_1 Myclass::add(const type_1 lva, const type_2 rva)
{
a = lva + rva;
return a;
}
template
template
class Myclass::Myclass_2
{
public:
type_3 value;
type_3 sub(const type_3 a , const type_3 b) {vlaue = a - b;}
};
建议别这么搞,要是类型匹配不上,那你真的脑壳痛~