c++ - User-defined implicit conversion operator and overload resolution -
this question has answer here:
today experienced interesting behaviour user-defined implicit conversion operators.
let's take piece of code:
struct widget { widget(uint64_t) { } widget(const std::string &) { } operator uint64_t() { return static_cast<uint64_t>(123456789ul); } operator std::string() { return std::string("hello"); } }; a basic struct can implicitly converted either uint64_t or std::string.
now, try print out widget instance through std::cout :
#include <iostream> int main() { using std::cout; widget w(123456); cout << w; } for whatever reason, widget converted uint64_t. @ first expect call ambiguous, , qualifed standard explicit conversion compile :
int main() { using std::cout; widget w(123456); cout << static_cast<uint64_t>(w); }
but reason i'm ignoring right now, operator uint64_t selected. tried @ c++ specification, couldn't find useful answer question.
can me figuring out compiler doing overload resolution ?
uint64_t conversion preferred. reason << overloaded template strings (basic_strings). compilers prefer exact match on templates on overload resolution.
Comments
Post a Comment