class Test {
public:
operator string() {
return string{"TEST!"};
}
};
int main() {
cout << Test{};
}
I was expecting the Test object will be implicit converted to a string and output, but it gives me error:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
This explicit conversion works:
cout << string{Test{}};
I got it working by casting to const char*
:
class Test {
public:
operator const char*() {
return "TEST!";
}
};
Then output:
cout << Test{}; //Yay it works.
I am assuming the cout << string
is already an implicit conversion from string
to char *
and if I use casting to string, it will not perform a two level conversion from Test to string to char *
. After directly casting to const char*
, it works. (Please correct if the assumption is wrong)
TO PROVE THE ASSUMPTION IS RIGHT
class Test {
public:
operator string() {
return string{"TEST!"};
}
};
ostream& operator<< (ostream& os, string s){
os << s;
return os;
}
This will perform a direct type deduction from Test to string
and output string. and after I tried, it works!
cout << Test{}; //YAY WORKS! OUTPUT "TEST!"
Something special about cout << string
is explained by Borgleader
. Assumption is partially correct and partially wrong.
– SwiftMango Aug 09 '13 at 19:27