Why is an implicit conversion operator to double preferred over a conversion to std::string?

Viewed 56

If I define multiple conversion operators for my class:

#include <iostream>
#include <string>

class Widget {
public:
    operator double() {
        return 42.1;
    }

    operator std::string() {
        return "string";
    }
};

int main(void) {
    Widget w;
    std::cout << w << std::endl;

    return 0;
}

the output of this is 42.1 even if I change the order of the member functions.

Why does the compiler always use operator double() instead of operator std::string()? What is the function resolve rules for this?

If I define the second conversion operator to int instead of std::string, the compiler will complain about an ambiguous call.

0 Answers
Related