C++运算符==和隐式转换解析
C++ operator == and implicit conversion resolution
如果我有一个 struct A
定义为:
struct A {
const char *data;
operator const char * () const { return data; }
friend bool operator== (const A &s1, const char *s2)
{ return /* typical string comparison result */; }
};
而我写A{"hello"} == "test2"
,是叫A::operator==
吗?标准中的内容说明(为什么 A
不隐式转换为 const char *
?)
那"test2" == A{"hello"}
呢?在这种情况下 A
是否已转换?
编辑:如果 struct A
也有成员:
怎么办
friend bool operator== (const char *s1, const A &s2)
当你这样做时
A{"hello"} == "test2"
我们对 operator==
执行重载决议。首先,我们通过名称查找找到可行的候选人([over.match.viable]):
operator==(A const&, const char*); // yours
operator==(const char*, const char*); // built-in
接下来,我们确定哪个候选者具有最佳隐式转换序列。这是 [over.match.best] 中的第一个决胜局:
Given these definitions, a viable function F1
is defined to be a better function than another viable function F2
if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
(1.3) — for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, [...]
两个运算符在第二个参数上都是完全匹配的。在第一个参数中,您的 operator==
是完全匹配,而内置需要用户定义的转换。精确匹配是最好的一种转换,而用户定义的是最差的 - 因此,您的转换顺序更好,成为最好的可行功能。
从广义上讲,A
不会隐式转换为 const char*
,因为有更好的选择,但不一定如此。
当你这样做时:
"test2" == A{"hello"};
您的候选者不可行 - 没有从 const char*
到 A const&
(第一个参数)的隐式转换,因此唯一可行的候选者是 [=18= 的内置比较], 这需要用户定义的从 A
到 const char*
.
的转换
如果您希望调用 A::operator==
,则必须为 operator==(const char*, A const&)
添加一个新的重载。
如果我有一个 struct A
定义为:
struct A {
const char *data;
operator const char * () const { return data; }
friend bool operator== (const A &s1, const char *s2)
{ return /* typical string comparison result */; }
};
而我写A{"hello"} == "test2"
,是叫A::operator==
吗?标准中的内容说明(为什么 A
不隐式转换为 const char *
?)
那"test2" == A{"hello"}
呢?在这种情况下 A
是否已转换?
编辑:如果 struct A
也有成员:
friend bool operator== (const char *s1, const A &s2)
当你这样做时
A{"hello"} == "test2"
我们对 operator==
执行重载决议。首先,我们通过名称查找找到可行的候选人([over.match.viable]):
operator==(A const&, const char*); // yours
operator==(const char*, const char*); // built-in
接下来,我们确定哪个候选者具有最佳隐式转换序列。这是 [over.match.best] 中的第一个决胜局:
Given these definitions, a viable function
F1
is defined to be a better function than another viable functionF2
if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
(1.3) — for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, [...]
两个运算符在第二个参数上都是完全匹配的。在第一个参数中,您的 operator==
是完全匹配,而内置需要用户定义的转换。精确匹配是最好的一种转换,而用户定义的是最差的 - 因此,您的转换顺序更好,成为最好的可行功能。
从广义上讲,A
不会隐式转换为 const char*
,因为有更好的选择,但不一定如此。
当你这样做时:
"test2" == A{"hello"};
您的候选者不可行 - 没有从 const char*
到 A const&
(第一个参数)的隐式转换,因此唯一可行的候选者是 [=18= 的内置比较], 这需要用户定义的从 A
到 const char*
.
如果您希望调用 A::operator==
,则必须为 operator==(const char*, A const&)
添加一个新的重载。