猿问

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

考虑以下代码:


#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的结合吗?


狐的传说
浏览 552回答 3
3回答

慕尼黑5688855

在C ++ 98中为14.8.1 / 4如果参数类型不包含参与模板参数推导的模板参数,则对函数参数执行隐式转换(第4节),以将其转换为相应的函数参数的类型。在这里您想实例化template <class charT, class traits, class Allocator>&nbsp; basic_ostream<charT, traits>&&nbsp; &nbsp; operator<<(basic_ostream<charT, traits>&,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const basic_string<charT, traits, Allocator>&);在没有明确提供任何模板参数的情况下进行推断。因此,所有参数都包含一个模板参数,该参数参与模板参数推导,因此它们都无法从隐式转换中获取其值。
随时随地看视频慕课网APP
我要回答