[英]How does the safe bool idiom bool_type (and the safe bool idiom) work?
我指着“安全布爾成語”,並試圖破譯后是怎么回事(說明該網站上提供的是不足夠的,足以給予我的,為什么它的工作原理的理解),我決定嘗試采取以下代碼並盡量簡化它。 該網站提供的代碼如下:
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_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
};
我決定分析 'bool_type' 的關鍵基礎,因為這似乎是它的中心。 鑒於以下行:
typedef void (Testable::*bool_type)() const;
可以(不太容易,由於括號)推斷它是一種類型為“void Testable::*”的 typedef,其中 bool_type 表示。 這可以通過進行以下修改和函數調用來進一步證明:
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) {}
bool_type Test; //Added this
operator bool_type() const {
return ok_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
};
int main()
{
Testable Test;
int A = Test.Test; //Compiler will give a conversion error, telling us what type .Test is in the process
}
它允許我們查看 bool_type 是什么類型:
錯誤:無法在初始化時將“void (Testable::*)()const”轉換為“int”
這表明它確實是一種“void (Testable::*)”。
問題出現在這里:
如果我們修改如下函數:
operator bool_type() const {
return ok_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
並將其變成:
operator void Testable::* () const //Same as bool_type, right?
{
return ok_==true ?
&Testable::this_type_does_not_support_comparisons : 0;
}
它會產生以下投訴:
錯誤:“*”標記之前的預期標識符
錯誤:“<無效運算符>”聲明為返回函數的函數
我的問題是:
如果 'void (Testable::*) 確實是 bool_type 的 typedef,為什么會產生這些抱怨?
和
這里發生了什么?
你的推理在這里出錯了
operator void Testable::* () const //Same as bool_type, right?
這不正確。 bool_type 的類型是,正如編譯器在錯誤消息中告訴我們的:
'void (Testable::*)()const'
因此,要在運算符中替換它,您需要類似的東西
operator (void (Testable::*)() const) () const
如果有可能的話! 明白為什么即使是丑陋的 typedef 也是一種改進嗎?
在 C++11 中,我們還有新的構造explicit operator bool()
來避免這種丑陋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.