c++ - Implicit type conversion is not working -
class test { public: operator string() { return string{"test!"}; } }; int main() { cout << test{}; } i expecting test object implicit converted string , output, gives me error:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue 'std::basic_ostream<char>&&' this explicit conversion works:
cout << string{test{}}; i got working casting const char*:
class test { public: operator const char*() { return "test!"; } }; then output:
cout << test{}; //yay works. i assuming cout << string implicit conversion string char * , if use casting string, not perform 2 level conversion test string char *. after directly casting const char*, works. (please correct if assumption wrong)
to prove assumption right
class test { public: operator string() { return string{"test!"}; } }; ostream& operator<< (ostream& os, string s){ os << s; return os; } this perform direct type deduction test string , output string. , after tried, works!
cout << test{}; //yay works! output "test!" something special cout << string explained borgleader. assumption partially correct , partially wrong.
the explicit keyword means have explicitly conversion std::string(test{}). disables implicit conversions.
cout << string{test{}}; // <-- explicit, you've got implicit , explicit confused the rule is, during template argument deduction, no user defined conversion attemped. however, you've noted if have conversion operator int compiles. because overload not function template. take @ reference page, , see:
basic_ostream& operator<<( int value ); this non-templated overload compiler user defined conversions.
Comments
Post a Comment