您的位置:首页 > 编程语言 > C语言/C++

c++类型形参的实参的受限转换

2013-09-25 20:52 183 查看
缘起:《c++ primer》 4th, 528页,习题16.3

源程序

#include <iostream>
#include <vector>
#include <list>
using namespace std;

template<class S>
int compare(const S &v1, const S &v2)
{
if (v1 < v2)
return -1;
else if(v1 > v2)
return 1;
else
return 0;
}

int main()
{
string s1 = "hi";
string s2 = "world";
cout << "string:" << compare(s1, s2) << endl;
cout << "hi:" << compare("hi", "world") << endl; }


错误提示



函数模板中定义的类型S,在函数的两个参数中,类型必须相同,但是编译错误,提示:一个类型为char[3],另一个类型为char[6].这就引出一条实参的受限转换。

数组或函数到指针的转换:如果模板形参不是引用类型,则对数组或函数类型的实参应该用常规指针转换。数组实参将当做指向第一个元素的指针,函数实参当做指向函数类型的指针。

下边程序就可以了

#include <iostream>
#include <vector>
using namespace std;

template<class S>
int compare(const S v1, const S v2)
{
if (v1 < v2)
return -1;
else if(v1 > v2)
return 1;
else
return 0;
}

int main()
{
char a[] = "abcd";
char b[] = "12345";
cout << compare(a, b) << endl;
}


注意直接传字串默认是const类型, 比如

#include <iostream>
#include <vector>
using namespace std;

template<class S>
int compare(const S v1, const S v2)
{
if (v1 < v2)
return -1;
else if(v1 > v2)
return 1;
else
return 0;
}

int main()
{
char a[] = "abcd";
char b[] = "12345";
cout << compare(a, "1234") << endl;
}


错误提示:



改成正确的:

#include <iostream>
#include <vector>
using namespace std;

template<class S>
int compare(const S v1, const S v2)
{
if (v1 < v2)
return -1;
else if(v1 > v2)
return 1;
else
return 0;
}

int main()
{
const char a[] = "abcd";
char b[] = "12345";
cout << compare(a, "1234") << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: