人工低能

Artificial Imbecility(AI) may bedefined as the branch of IQ hat is concerned with the automation of imbecility behavior

原创 混沌 IN C++::转换函数收藏

新一篇: 混沌 IN C++::is-a的误解 | 旧一篇: 混沌 IN C++::Argument Dependent Lookup

难度:

问题:

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

 

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...)|编辑|收藏

新一篇: 混沌 IN C++::is-a的误解 | 旧一篇: 混沌 IN C++::Argument Dependent Lookup

评论

#fr3ak 发表于2008-09-10 11:06:17  IP: 122.116.52.*
好文.

文中最后一段有个小小笔误:
> 而是被实例化成basic_string<wchar_t>这个模板类

其中的 template parameter, wchar_t, 应为 char.
2008-09-10 12:04:17作者回复
Sorry,谢谢指正。
发表评论  


当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
Csdn Blog version 3.1a
Copyright © Jinhao