template
void myfunc(T tmpvalue)
{
cout << "myfunc(T tmpvalue)执行了" << endl;
}
myfunc(12); // 输出 myfunc(T tmpvalue)执行了
char* p = nullptr;
myfunc(p); // 输出 myfunc(T tmpvalue)执行了
下面进行模板重载
template
void myfunc(T tmpvalue)
{
cout << "myfunc(T tmpvalue)执行了" << endl;
}
template
void myfunc(T* tmpvalue)
{
cout << "myfunc(T* tmpvalue)执行了" << endl;
}
myfunc(12);
char* p = nullptr;
myfunc(p);
myfunc(T tmpvalue)执行了
myfunc(T* tmpvalue)执行了
template
void myfunc(T tmpvalue)
{
cout << "myfunc(T tmpvalue)执行了" << endl;
}
template
void myfunc(T* tmpvalue)
{
cout << "myfunc(T* tmpvalue)执行了" << endl;
}
void myfunc(int tmpvalue)
{
cout << "myfunc(int tmpvalue)执行了" << endl;
}
myfunc(12);
char* p = nullptr;
myfunc(p);
myfunc(12.1);*/
myfunc(int tmpvalue)执行了
myfunc(T* tmpvalue)执行了
myfunc(T tmpvalue)执行了
template
void tfunc(T& tmprv, U& tmprv2)
{
cout << "tfunc泛化版本" << endl
cout << tmprv << endl;
cout << tmprv2 << endl;
}
const char* p = "I Love China!";
int i = 12;
tfunc(p, i);
T = const char *;
U = int
tmprv = const char * &
tmprv2 = int &
template <> //全特化<>里面为空
void tfunc(int& tmprv, double& tmprv2)//可以省略,因为根据实参可以完全推导出T和U的类型。
//void tfunc(int& tmprv, double& tmprv2)
{
cout << "tfunc特化版本" << endl;
cout << tmprv << endl;
cout << tmprv2 << endl;
}
int k = 12;
double db = 15.8;
tfunc(k, db);
//全特化
template <>
void tfunc(int& tmprv, double& tmprv2)
{
cout << "tfunc特化版本" << endl;
cout << tmprv << endl;
cout << tmprv2 << endl;
}
//重载函数
void tfunc(int& tmprv, double& tmprv2)
{
cout << "tfunc普通函数" << endl;
}
int k = 12;
double db = 15.8;
func(k, db);
//从模板参数数量上的偏特化
template
void tfunc(double& tmprv, U& tmprv2)
{
//.......
}
template
void myfunc(T tmpvalue)
{
cout << "myfunc(T tmpvalue)执行了" << endl;
}
template
void tfunc(const T& tmprv, U& tmprv2)
{
cout << "tfunc(const T& tmprv, U& tmprv2)重载版本" << endl;
}
const int k2 = 12;
tfunc(k2, db);
tfunc(const T& tmprv, U& tmprv2)重载版本
//泛化版本
template
void tfunc(T& tmprv, U& tmprv2)
{
cout << "tfunc泛化版本" << endl
cout << tmprv << endl;
cout << tmprv2 << endl;
}
//重载
template
void tfunc(double& tmprv, U& tmprv2)
{
cout << "类似于tfunc偏特化的tfunc重载版本" << endl;
cout << tmprv << endl;
cout << tmprv2 << endl;
}
double j = 18.5;
tfunc(j, i);
类似于tfunc偏特化的tfunc重载版本