您的位置:首页 > 其它

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

2017-04-25 14:09 218 查看
#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值不同则两个字符串所对应的类型就不同,因此不能实例化同一个模版参数。而对于非引用
类型的字符串参数,编译器会自动将字符数组转换为字符指针类型,所以不同长度的字符串都会转换为相同额
字符指针类型,因此可以实例化同一个模版参数。
下面的代码是对于此结论的验证代码:
*/ 

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息