为了账号安全,请及时绑定邮箱和手机立即绑定

通过隐式转换为字符串流对象时,过载解析失败

通过隐式转换为字符串流对象时,过载解析失败

C++
狐的传说 2019-11-02 10:42:56
考虑以下代码:#include <string>#include <ostream>#include <iostream>struct NameType {   operator std::string() { return "wobble"; }};struct Person {   NameType name;};int main() {   std::cout << std::string("bobble");   std::cout << "wibble";   Person p;   std::cout << p.name;}它产生于GCC 4.3.4以下:prog.cpp: In function ‘int main()’:prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]op<<(ostream&, string const&)为何免费不将其纳入过载组?这是由于所需的重载是模板实例化和... ADL的结合吗?
查看完整描述

3 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

在C ++ 98中为14.8.1 / 4


如果参数类型不包含参与模板参数推导的模板参数,则对函数参数执行隐式转换(第4节),以将其转换为相应的函数参数的类型。


在这里您想实例化


template <class charT, class traits, class Allocator>

  basic_ostream<charT, traits>&

    operator<<(basic_ostream<charT, traits>&,

               const basic_string<charT, traits, Allocator>&);

在没有明确提供任何模板参数的情况下进行推断。因此,所有参数都包含一个模板参数,该参数参与模板参数推导,因此它们都无法从隐式转换中获取其值。


查看完整回答
反对 回复 2019-11-02
  • 3 回答
  • 0 关注
  • 551 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信