我已经看到了 boost 实现的一个很好的技巧,他们以某种方式使用 () 运算符的重载来将类 boost::system::error_code 的实例评估为 bool 值
class error_code
{
...
typedef void (*unspecified_bool_type)();
static void unspecified_bool_true() {}
operator unspecified_bool_type() const // true if error
{
return m_val == 0 ? 0 : unspecified_bool_true;
}
...
}
这导致检查这样的错误的可能性
...
boost::system::error_code err
some_boost_func(err);
if(err)
{
//handle error
}
....
所以我一直在问自己..那里发生了什么?这似乎与函数指针的使用有关......如果我调用err
它会评估函数本身或函数指针会发生什么?但是函数如何void (*unspecified_bool_type)();
返回值
return m_val == 0 ? 0 : unspecified_bool_true;