难度:

问题:
下面这段代码为什么会编译失败呢?
struct T
{
operator
std::string() const
{
return
std::string();
}
operator
int() const
{
return
int();
}
};
int
main()
{
T t;
int
i = t;
std::string s = t;
i == t; //成功
s == t; //失败
}
回答:
因为标准库没有提供bool operator==(const
std::string&, const std::string&);这样的重载,而是提供了
template<typename CharT, typename
Traits, typename Alloc>
bool
operator==(const std::basic_string<CharT, Traits, Alloc>&, const 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<typename CharT, typename
Traits, typename Alloc>
basic_string(const basic_string<CharT, Traits, Alloc>&);
按照上面的说法,那显式转换std::string(t)是怎么完成推导函数模板参数的呢? 其实std::string并不是类模板了,而是被实例化成basic_string<char>这个模板类,std::string(t)也没有进行推导,因为已经明确了CharT, Traits,
Alloc这三个模板参数,所以这时的operator std::string() const起作用了。
发表于 @ 2008年09月08日 14:48:00|评论(loading...)|编辑|收藏