Consider the following struct with a user-defined conversion function that can convert itself to const char*;
struct S {
operator const char*() { return "hello"; }
};
This work with <iostream>, we can print the struct S with no error message:
std::cout << S{} << '\n';
But if I change the return type to std::string:
struct S {
operator std::string() { return "hello"; }
};
I got this compiler error message:
<source>:11:13: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'S')
11 | std::cout << S{} << '\n';
| ~~~~~~~~~ ^~ ~~~
| | |
| | S
| std::ostream {aka std::basic_ostream<char>}
<source>:11:18: note: 'S' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Allocator>'
11 | std::cout << S{} << '\n';
| ^
Why can't the compiler use the std::string conversion? Is there a difference between the conversion function of the built-in and class type?