[問題] Safe Bool Idiom

看板C_and_CPP (C/C++)作者 (王大明)時間2年前 (2021/06/08 19:13), 2年前編輯推噓1(108)
留言9則, 3人參與, 2年前最新討論串1/1
開發平台(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

06/08 20:37, 2年前 , 1F
function pointer to member function
06/08 20:37, 1F

06/08 21:17, 2年前 , 2F

06/08 21:19, 2年前 , 3F
把上面這一頁從頭到尾讀懂就會知道這程式碼的來龍去脈了
06/08 21:19, 3F

06/08 21:20, 2年前 , 4F
你大概是讀到 wikibook, 記得要連下面的參考資料也要看看
06/08 21:20, 4F

06/09 01:09, 2年前 , 5F
第一個寫成 using bt = void (Testable::*)() const;
06/09 01:09, 5F

06/09 01:09, 2年前 , 6F
這樣有沒有比較好理解
06/09 01:09, 6F

06/09 01:10, 2年前 , 7F
bt是個pointer to Testable裡的function
06/09 01:10, 7F

06/09 01:10, 2年前 , 8F
第二個是標準規定的, address of用在
06/09 01:10, 8F

06/09 01:10, 2年前 , 9F
non-static member functions一定要qualified
06/09 01:10, 9F
文章代碼(AID): #1Wlr3dtZ (C_and_CPP)
文章代碼(AID): #1Wlr3dtZ (C_and_CPP)