本文学习自 狄泰软件学院 唐佐林老师的 C++课程,文中图片源自老师课程PPT。
实验1:类模板的特化
实验2:特化的深入理解:函数模板的完全特化
实验1:类模板的特化
#include
#include
using namespace std;
template
class Test
{
public:
void add(T1 a, T2 b)
{
cout << "void add(T1 a, T2 b)" << endl;
cout << a + b << endl;
}
};
template
class Test // 关于指针的特化
{
public:
void add(T1* a, T2* b)
{
cout << "void add(T1* a, T2* b)" << endl;
cout << *a + *b << endl;
}
};
template
class Test //部分特化, 当 Test 类模板的两个类型参数完全相同时,使用这个实现
{
public:
void add(T a, T b)
{
cout << "void add(T a, T b)" << endl;
cout << a + b << endl;
}
void print()
{
cout << "class Test " << endl;
}
};
template
class Test // 完全特化,当 T1 == void* 并且 T2 == void* ʱ
{
public:
void add(void* a, void* b)
{
cout << "void add(void* a, void* b)" << endl;
cout << "Error to add void* param..." << endl;
}
};
int main()
{
Test t1;
Test t2;
Test t3;
t1.add(1, 2.5);
t2.add(5, 5);
t2.print();
t3.add(NULL, NULL);
Test t4;
int a = 1;
double b = 0.1;
t4.add(&a, &b);
return 0;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 59-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
void add(T1 a, T2 b)
3.5
void add(T a, T b)
10
class Test
void add(void* a, void* b)
Error to add void* param...
void add(T1* a, T2* b)
1.1
mhr@ubuntu:~/work/c++$
类模板的特化实现在表面上好像是我们定义了不同的类模板,但是其实不是,我们仅仅是根据需要将一个类模板分开成不同的情况来实现。
实验2:特化的深入理解:函数模板的完全特化
#include
#include
using namespace std;
template
class Test
{
public:
void add(T1 a, T2 b)
{
cout << "void add(T1 a, T2 b)" << endl;
cout << a + b << endl;
}
};
class Test_Void
{
public:
void add(void* a, void* b)
{
cout << "void add(void* a, void* b)" << endl;
cout << "Error to add void* param..." << endl;
}
};
template
bool Equal(T a, T b)
{
cout << "bool Equal(T a, T b)" << endl;
return a == b;
}
template
bool Equal(double a, double b)
{
const double delta = 0.00000000000001;
double r = a - b;
cout << "bool Equal(double a, double b)" << endl;
return (-delta < r) && (r < delta);
}
bool Equal(double a, double b)
{
const double delta = 0.00000000000001;
double r = a - b;
cout << "bool Equal(double a, double b)" << endl;
return (-delta < r) && (r < delta);
}
int main()
{
cout << Equal( 1, 1 ) << endl;
//编译器回优先的选择全局的重载函数。
//cout << Equal( 0.001, 0.001 ) << endl;// cout << "bool Equal(double a, double b)" << endl;
cout << Equal( 0.001, 0.001 ) << endl;//放弃全局重载函数,只使用函数模板。
return 0;
}
mhr@ubuntu:~/work/c++$ g++ 59-2.cpp
mhr@ubuntu:~/work/c++$ ./a.out
bool Equal(T a, T b)
1
bool Equal(double a, double b)
1
mhr@ubuntu:~/work/c++$