2011-10-09 62 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

回答这个问题/对这个问题做了一个很好的猜测/ –