2011-10-09 43 views
0

我被指出'安全布爾成語',並試圖破譯發生了什麼(解釋supplied on the site是不夠的,不足以讓我瞭解爲什麼它的工作原理),我決定嘗試採取以下將代碼分開並嘗試儘可能簡化它。下面的網站提供的代碼:安全bool成語bool_type(和安全bool成語)是如何工作的?

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; 

人們可以(不是那麼容易,因爲包圍)推斷這是一個類型的「無效可測試:: *」,其中bool_type代表的一個typedef。這可以通過以下修改和功能進一步顯現電話:

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是:

error: cannot convert 'void (Testable::*)()const' to 'int' in initialization

這表明它確實是一個類型爲「無效(可測試:: *)」。

的問題,在這裏作物起來:

如果我們修改了以下功能:

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; 
    } 

生成下面投訴:

error: expected identifier before '*' token
error: '< invalid operator >' declared as function returning a function

我的問題是這樣的:

如果'void(Testable :: *)確實是bool_type的typedef,它爲什麼會產生這些抱怨?

And

這是怎麼回事?

+1

爲什麼一個人在標題中提出一個問題,然後在文本中提出一個完全不同的問題?更不用說*兩個*這樣非常不同的問題了? –

+0

問題是什麼?'bool_type'是一個指向成員函數的指針,指向'void Testable :: some_function()const'類型的函數。 「由於包圍」沒有混淆(儘管C++聲明語法不完全是美的縮影)。 –

+0

我從來沒有說過這個詞的困惑,我只是說,推測(Testable :: * bool_type)乍看起來似乎是一個指向名爲bool_type的變量的指針並不容易。除了不是,給定typedef意味着最後一個詞是typedef之後的所有內容。儘管它被括起來(與優先級相反)。 – SSight3

回答

3

你的推理出錯有關此

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()將我們從這個醜陋中拯救出來。

+0

讓我猜測,顯式使其僅適用於bools?聰明的想法。並感謝你真正回答這個問題。 – SSight3

+1

回答這個問題/對這個問題做了一個很好的猜測/ –