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

混沌 IN C++::转换函数

2008-09-08 14:48 369 查看
难度:




问题:

下面这段代码为什么会编译失败呢?



struct[/b] T

{

operator[/b]
std::string() const[/b]

{

return[/b]
std::string();

}



operator[/b]
int[/b]() const[/b]

{

return[/b]
int[/b]();

}

};



int[/b]
main()

{

T t;

int[/b]
i = t;

std::string s = t;



i == t; //成功

s == t; //失败

}



回答:

因为标准库没有提供bool[/b] operator[/b]==(const[/b]
std::string&, const std::string&);这样的重载,而是提供了

template[/b]<typename[/b] CharT, typename[/b]
Traits, typename[/b] Alloc>

bool[/b]
operator[/b]==(const[/b] std::basic_string<CharT, Traits, Alloc>&, const[/b] std::basic_string<CharT,
Traits, Alloc>&);



当s == t 进行比较的时候,编译器用第一个参数s可以推导出CharT, Traits, Alloc这三个模板参数,然后用t来推导,结果是无法完成推导,因为t并不是basic_string<>。那T中的operator std::string() const的转换函数在这里有什么作用呢?事实上,这个转换函数在这里一点用也没有,C++没有提供一个规则是先转换再推导函数模板参数的。解决这个问题的办法,就是让编译器在推导第二个参数的类型之前,显式地将t转换为std::string。

s == std::string(t);



到这一步,有人又会纳闷,basic_string也没提供basic_string(const
std::string&)的构造函数啊,而是提供的

template[/b]<typename[/b] CharT, typename[/b]
Traits, typename[/b] Alloc>

basic_string(const[/b] basic_string<CharT, Traits, Alloc>&);

按照上面的说法,那显式转换std::string(t)是怎么完成推导函数模板参数的呢? 其实std::string并不是类模板了,而是被实例化成basic_string<char>这个模板类,std::string(t)也没有进行推导,因为已经明确了CharT, Traits,
Alloc这三个模板参数,所以这时的operator std::string() const起作用了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: