1

In the next example, why the operator << prefer to cast to double rather than to string? Is it because primitive have higher priority?

class R {
public:
    R(double x) : _x(x) {}
    operator string () {cout << "In string operator\n"; return std::to_string(_x);}
    operator double () {cout << "In double operator\n"; return _x;}
private:
    double _x;
};

int main() {
    R r(2.5);
    cout << r << endl;
    return 0;
}
user890739
  • 702
  • 1
  • 13
  • 33

1 Answers1

0

It's because operator std::string() simply isn't viable. The operator<< overload taking basic_strings is

template<class charT, class traits, class Allocator>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>& os, const basic_string<charT,traits,Allocator>& str);

And template argument deduction can't deduce the template arguments from the type R. It won't look through implicit conversions.

You can see this by commenting out operator double and watching your code explode.

T.C.
  • 133,968
  • 17
  • 288
  • 421