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

rel="File-List" href="file:///C:%5CUsers%5CADMINI%7E1%5CAppData%5CLocal%5CTemp%5Cmsohtml1%5C02%5Cclip_filelist.xml">

难度:

问题:

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

 

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起作用了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值