为什么编译器不执行类型转换?
考虑以下代码。
#include <iostream>
#include <string>
struct SimpleStruct
{
operator std::string () { return value; }
std::string value;
};
int main ()
{
std::string s; // An empty string.
SimpleStruct x; // x.value constructed as an empty string.
bool less = s < x; // Error here.
return 0;
}
此代码无法在 g++ 或 Microsoft Visual C++ 上编译。编译器给出的错误报告是 no match for operator '<'在 的 < x'
。问题是为什么编译器不简单地根据给定的operator string ()
将SimpleStruct x
转换为string
,然后使用运算符 < (字符串,字符串)
?
Consider the following code.
#include <iostream>
#include <string>
struct SimpleStruct
{
operator std::string () { return value; }
std::string value;
};
int main ()
{
std::string s; // An empty string.
SimpleStruct x; // x.value constructed as an empty string.
bool less = s < x; // Error here.
return 0;
}
This code does not compile either on g++ or Microsoft Visual C++. The error report given by compilers is no match for operator '<' in 's < x'
. The question is why does the compiler not simply convert the SimpleStruct x
to string
according to the given operator string ()
and then use operator < ( string, string )
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::string
的operator<
是一个函数模板。重载是:您的调用与任何可用的重载都不匹配,因此它们都从候选列表中删除。由于没有选择函数模板作为解析调用的候选函数,因此没有任何内容可以将 SimpleStruct 转换为。
operator<
forstd::string
is a function template. The overloads are:Your call doesn't match any of the available overloads, so they are all removed from a list of candidates. Since no function template was picked as a candidate for resolving the call, there is nothing to convert SimpleStruct to.