from the answer, I learned std::string
is just typedef of std::basic_string<char, std::char_traits<char>, std::allocator<char>>
, Template argument substitution does not consider user-defined conversions, so the compiler can't deduce the types CharT, Traits, or Allocator from the type Rectangle, so this overload does not participate in overload resolution.
Now I substitute std::basic_string, std::allocator> for std::string:
class Rectangle
{
public:
Rectangle(double x, double y) : _x(x), _y(y) {}
operator std::basic_string<char, std::char_traits<char>, std::allocator<char>> () {
return std::basic_string<char, std::char_traits<char>, std::allocator<char>>(to_string(_x) + " " + to_string(_y));
}
//operator double() {
// return _x;
//}
private:
double _x, _y;
double getArea() { return _x * _y; }
};
int main()
{
Rectangle r(3, 2.5);
cout << r << endl;
return 0;
}
It still fails. Why?
template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits>& os,
const std::basic_string<CharT, Traits, Allocator>& str);