4

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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
guorongfei
  • 309
  • 2
  • 10
  • 2
    generally speaking, conversion to non-class type is preferred to conversion to class type – M.M May 21 '17 at 12:42
  • 2
    @InternetAussie Evidently, there is some rule that establishes some order in this case (or the compiler thinks so at least) and the question is what standard rule applies. – Baum mit Augen May 21 '17 at 12:45
  • @BaummitAugen Ah, okay. I see. –  May 21 '17 at 12:46
  • 5
    My guess would be that it is because the streaming operators for strings are templated and the non-templated one for doubles are preferred. – MikeMB May 21 '17 at 12:46

0 Answers0