作者WangDaMing (王大明)
看板C_and_CPP
标题[问题] Safe Bool Idiom
时间Tue Jun 8 19:13:41 2021
开发平台(Platform): (Ex: Win10, Linux, ...)
Linux
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
GCC
问题(Question):
class Testable {
bool ok_;
typedef void (Testable::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
explicit Testable(bool b=true):ok_(b) {}
operator bool_type() const {
return ok_ ?
&Testable::this_type_does_not_support_comparisons : 0;
}
};
最近学C++看到这个Safe bool idiom,我知道C++11有其他写法
可是我想不懂为何里面都需要加"Testable::"这个,为何一定要写,
不然编译不过,不是很懂为何都在class内了还要特别写,这是哪条规则??
感谢!!
※ 编辑: WangDaMing (39.11.68.163 台湾), 06/08/2021 19:16:43
1F:→ nh60211as: function pointer to member function 06/08 20:37
3F:→ LPH66: 把上面这一页从头到尾读懂就会知道这程式码的来龙去脉了 06/08 21:19
4F:→ LPH66: 你大概是读到 wikibook, 记得要连下面的参考资料也要看看 06/08 21:20
5F:→ g0010726: 第一个写成 using bt = void (Testable::*)() const; 06/09 01:09
6F:→ g0010726: 这样有没有比较好理解 06/09 01:09
7F:→ g0010726: bt是个pointer to Testable里的function 06/09 01:10
8F:→ g0010726: 第二个是标准规定的, address of用在 06/09 01:10
9F:→ g0010726: non-static member functions一定要qualified 06/09 01:10