字符串作为函数模版实參的意外情况

有时,当把c风格的不同字符串去实例化函数模版的同一个模版參数时,在实參演绎的过程中常常会发生

意想不到的事情,那就是编译失败,并报错类型不匹配。

正如以下的样例一样:

#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);
}

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

}
对于上述这样的情况的解释就是:对于引用类型的字符串參数编译器会自己主动转换成“字符常量数组”比如const char[N],所以假设N值不同则两个字符串所相应的类型就不同,因此不能实例化同一个模版參数。而对于非引用

类型的字符串參数,编译器会自己主动将字符数组转换为字符指针类型,所以不同长度的字符串都会转换为同样额

字符指针类型,因此能够实例化同一个模版參数。

以下的代码是对于此结论的验证代码:

#include<iostream>
using namespace std;

/*
*类型測试
*/
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()
{
	//输出引用字符串的类型
	Ref("abc");
	//输出非引用字符串的类型
	nonRef("abc");

	/*
	输出结果:
	abcref:char const [4]
        abcref:char const *
        请按随意键继续. . .
        */
}




posted @ 2014-08-14 12:34  zfyouxi  阅读(218)  评论(0编辑  收藏  举报