#include <iostream>
#include <string>
using namespace std;
class Test
{
//拷贝构造函数为私有,说明不能进行拷贝构造
Test(const Test&);
public:
Test()
{
}
};
template < typename T >
void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
typedef void(FuncI)(int&, int&);
typedef void(FuncD)(double&, double&);
typedef void(FuncT)(Test&, Test&);
int main()
{
FuncI* pi = Swap; // 编译器自动推导 T 为 int
FuncD* pd = Swap; // 编译器自动推导 T 为 double
// FuncT* pt = Swap; // 编译器自动推导 T 为 Test
//reinterpret_cast:1、用于指针间的转换!2、用于指针和整数间的转换!
cout << "pi = " << reinterpret_cast<void*>(pi) << endl;//上下两个指针输出的值不一样
cout << "pd = " << reinterpret_cast<void*>(pd) << endl;
// cout << "pt = " << reinterpret_cast<void*>(pt) << endl;
return 0;
}
如果像以上代码一样编写,编译时不会报错!编译器只会对模板函数进行一次编译,因为// FuncT* pt = Swap;被注释掉了。
如果加上FuncT* pt = Swap;(取消注释),那么编译器会报错!因为编译器会对模板函数二次编译,第一次编译不报错,第二次编译发现函数内存在:T c = a;这一行代码,这是会调用拷贝构造的,但是拷贝构造是私有的,所以报错!
#include <iostream>
#include <string>
using namespace std;
template
< typename T1, typename T2, typename T3 >
T1 Add(T2 a, T3 b)
{
return static_cast<T1>(a + b);
}
int main()
{
// T1 = int, T2 = double, T3 = double
int r1 = Add<int>(0.5, 0.8);
// T1 = double, T2 = float, T3 = double
double r2 = Add<double, float>(0.5, 0.8);
// T1 = float, T2 = float, T3 = float
float r3 = Add<float, float, float>(0.5, 0.8);
cout << "r1 = " << r1 << endl; // r1 = 1
cout << "r2 = " << r2 << endl; // r2 = 1.3
cout << "r3 = " << r3 << endl; // r3 = 1.3
return 0;
}
double r2 = Max<>(0.5,0.8);这么写是告诉编译器只考虑模板函数(<>:自动匹配类型),不考虑普通函数
#include <iostream>
#include <string>
using namespace std;
template < typename T >
T Max(T a, T b)
{
cout << "T Max(T a, T b)" << endl;
return a > b ? a : b;
}
int Max(int a, int b)
{
cout << "int Max(int a, int b)" << endl;
return a > b ? a : b;
}
template < typename T >
T Max(T a, T b, T c)
{
cout << "T Max(T a, T b, T c)" << endl;
return Max(Max(a, b), c);
}
int main()
{
int a = 1;
int b = 2;
cout << Max(a, b) << endl; // 普通函数 Max(int, int)
cout << Max<>(a, b) << endl; // 函数模板 Max<int>(int, int)
cout << Max(3.0, 4.0) << endl; // 函数模板 Max<double>(double, double)
cout << Max(5.0, 6.0, 7.0) << endl; // 函数模板 Max<double>(double, double, double)
cout << Max('a', 100) << endl; // 普通函数 Max(int, int)
return 0;
}