[問題] Safe Bool Idiom

作者: WangDaMing (王大明)   2021-06-08 19:13:41
開發平台(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
作者: nh60211as   2021-06-08 20:37:00
function pointer to member function
作者: LPH66 (-6.2598534e+18f)   2021-06-08 21:17:00
https://www.artima.com/articles/the-safe-bool-idiom把上面這一頁從頭到尾讀懂就會知道這程式碼的來龍去脈了你大概是讀到 wikibook, 記得要連下面的參考資料也要看看
作者: g0010726 (Kevin)   2021-06-09 01:09:00
第一個寫成 using bt = void (Testable::*)() const;這樣有沒有比較好理解bt是個pointer to Testable裡的function第二個是標準規定的, address of用在non-static member functions一定要qualified

Links booklink

Contact Us: admin [ a t ] ucptt.com