2017-02-20 15 views
6

जब मैं इस तरह कोड लिखने:अंतर्निहित रूपांतरण और उपयोगकर्ता परिभाषित रूपांतरण

struct foo { 
    operator int() const { return 1; } 
}; 
int main() { 
    foo a, b; 
    auto tmp = (a < b); 
} 

यह काम करता है, लेकिन जब मैं इस तरह कोड लिखने:

struct foo { 
    operator string() const { return string("foo"); } 
}; 
int main() { 
    foo a, b; 
    auto tmp = (a < b); 
} 

संकलक (बजना ++) का कहना है कि error: invalid operands to binary expression ('foo' and 'foo')

मुझे आश्चर्य है कि, क्यों string प्रकार और int प्रकार तुलना ऑपरेटर हैं, लेकिन जब foo में उपयोगकर्ता defi है ned int रूपांतरण, यह int पर तुलना करने के लिए निहित होगा, हालांकि foo केवल उपयोगकर्ता को string रूपांतरण परिभाषित किया गया है, संकलक अंतर्निहित रूपांतरण नहीं करता है हालांकि (string)a<(string)b अच्छी तरह से काम करता है।

+1

मैं न std::string एक टेम्पलेट की एक विशेषज्ञता, विशेष रूप से std::basic_string<char>

तो operator < रूप

template <class CharT, class Traits, class Allocator> bool operator< (const std::basic_string<CharT, Traits, Allocator> &_Left, const std::basic_string<CharT, Traits, Allocator> &_Right); 

यह के साथ काम करेंगे परिभाषित किया जाता है इस नियम का पता लगाएं जो इसका कारण बनता है, लेकिन अधिकांश एल आसानी से 'int' टाइप – user463035818

+4

संबंधित/डुप्ली के साथ कुछ करने के लिए कुछ है: http://stackoverflow.com/questions/42252023/implicit-conversion-operator-priority – NathanOliver

+0

@NathanOliver imho प्रश्न वास्तव में एक डुप्ली नहीं है, लेकिन जवाब में यह भी एक – user463035818

उत्तर

1

मुझे लगता है कि समस्या यह है कि स्ट्रिंग एक मूल प्रकार नहीं है।

auto tmp = (static_cast<std::string>(a) < static_cast<std::string>(b)); 

फिर operator < हो जाता है::

bool std::operator< <char, std::char_traits<char>, std::allocator<char>>(const std::string &_Left, const std::string &_Right) 
+2

कुछ याद आया और चूंकि उपयोगकर्ता परिभाषित रूपांतरण टेम्पलेट फ़ंक्शन विशेषज्ञता के लिए नहीं माना जाता है। यह संबंधित उत्तर देखें: [http://stackoverflow.com/questions/42252023/implicit-conversion-operator-priority/42253006#42253006]। – Oliv

संबंधित मुद्दे