隐式转换和用户定义的转换

问题描述:

当我写这样的代码:隐式转换和用户定义的转换

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

我不知道导致这一点的规则,但大多数l可能它与'int'有关,因为它是一个内置类型 – user463035818

+4

related/dupe:http://stackoverflow.com/questions/42252023/implicit-conversion-operator-priority – NathanOliver

+0

@NathanOliver imho问题不是真的是一个愚蠢的,但答案完美地解释了这一个 – user463035818

我认为问题在于字符串不是基本类型。 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); 

它将与合作:

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#42​​253006]。 – Oliv