Pin*_*tle 2 c++ operator-overloading
#include <cstdint>
#include <iostream>
struct a_struct {
int64_t* le_int;
bool not_ok;
a_struct() : le_int{ new int64_t(0) }, not_ok{ false } {}
~a_struct() { delete le_int; }
operator bool() const {
return !not_ok;
}
operator int64_t* () {
return le_int;
}
};
int main(int argc, char** argv) {
a_struct s;
s.not_ok = true;
if (!s)//<-
std::cout << "o no." << std::endl;
else if (s.not_ok)
std::cout << "waddu heck?" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,!s解决方案更倾向于使用int64_t*()运算符而不是 constbool()运算符。
为什么?
这是重载解析的“通过转换函数初始化”情况:http://eel.is/c++draft/over.match.conv
这两个转换函数都是候选函数,因为它们都是非显式的,并且它们的返回类型可以隐式转换为bool. 然后,以对象表达式s作为实参,以转换函数的隐含对象参数作为参数,执行重载解析。隐含的对象参数的类型为T cv &,其中T是类。
绑定T&到比绑定到T更好。这是隐式转换序列排序的规则之一。http://eel.is/c++draft/over.ics.rank#3.2.6T const&T
请注意,有一个涉及转换函数返回类型的决胜规则。仅在对每个参数的隐式转换序列进行排序未能产生最佳可行函数之后才考虑这种决胜规则,因为每个参数的隐式转换序列既不比相应参数的隐式转换序列更好也不更差。另一个功能。因此,仅当两个转换函数具有相同的 cv 限定(导致隐含对象参数的隐式转换序列相同)时,才能达到决胜局。http://eel.is/c++draft/over.match.best#general-2.2