字符串作为函数模版实参的特殊情况

来源:互联网 发布:淘宝聚划算是正品吗 编辑:程序博客网 时间:2024/06/09 00:29
#include  "stdafx.h"
#include<iostream>  
using namespace std;


/*
*匹配测试
*/
template<typename T>
int ref_fun(T & t1, T & t2)
{
return strlen(t1) - strlen(t2);
}


template<typename T>
int nonref_fun(T t1, T t2)
{
return strlen(t1) - strlen(t2);
}


/*
*类型测试
*/
template<typename T>
void Ref(T & t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}


template<typename T>
void nonRef(T t)
{
cout << t << "ref:" << typeid(t).name() << endl;
}




int main()
{
//int a = ref_fun("abcd","abc");  
//Error:没有与参数列表匹配的模版实例  
//参数类型为(const char[5],const char[4])  


int a = ref_fun("abcd","efgh");   
//编译通过  为(const char[5],const char[5])  
 
int b = nonref_fun("abcd", "abc");
//编译通过   为char *
/*
 解释:对于引用类型的字符串参数编译器会自动转换成“字符常量数组”例如const char[N],所以如果N值不同则两个字符串所对应的类型就不同,因此不能实例化同一个模版参数。而对于非引用
类型的字符串参数,编译器会自动将字符数组转换为字符指针类型,所以不同长度的字符串都会转换为相同额
字符指针类型,因此可以实例化同一个模版参数。
下面的代码是对于此结论的验证代码:
*/ 


//输出引用字符串的类型  
Ref("abc");
//输出非引用字符串的类型  
nonRef("abc");


}
0 0
原创粉丝点击