Dlaczego wyświetlanie klasy z operatorem konwersji nie działa dla std :: string?
#include <iostream>
struct Int {
int i;
operator int() const noexcept {return i;}
};
int main() {
Int i;
i.i = 1;
std::cout << i;
}
Jednak,nie uda się to skompilować w GCC 4.8.1:
#include <iostream>
#include <string>
struct String {
std::string s;
operator std::string() const {return s;}
};
int main() {
String s;
s.s = "hi";
std::cout << s;
}
Oto odpowiednie części błędu:
błąd: brak dopasowania dla „operatora <<” (typy operandów to „std :: ostream {aka std :: basic_ostream}” i „String”)
std :: cout << s;
fantastyczna okazja
szablon std :: basic_ostream <_CharT, _Traits> & std :: operator << (std :: basic_ostream <_CharT, _Traits> &, const std :: basic_string <_CharT, _Traits, _Alloc> &)
operator << (basic_ostream <_CharT, _Traits> & __os,
/usr/include/c++/4.8/bits/basic_string.h:2753:5: uwaga: odrzucenie / zastąpienie argumentu szablonu nie powiodło się:
main.cpp: 25: 18: uwaga: „String” nie pochodzi z „const std :: basic_string <_CharT, _Traits, _Alloc>”
std :: cout << s;
Używam tylkostd::cout
istd::string
, które mają te same argumenty szablonu. Naprawdę nie jestem pewien, dlaczego nie byłaby w stanie odebrać ukrytej konwersji, jak to miało miejsceInt
. Dlaczego to działaint
, ale niestd::string
?