我被指出'安全布尔成语',并试图破译发生了什么(解释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
这是怎么回事?
为什么一个人在标题中提出一个问题,然后在文本中提出一个完全不同的问题?更不用说*两个*这样非常不同的问题了? –
问题是什么?'bool_type'是一个指向成员函数的指针,指向'void Testable :: some_function()const'类型的函数。 “由于包围”没有混淆(尽管C++声明语法不完全是美的缩影)。 –
我从来没有说过这个词的困惑,我只是说,推测(Testable :: * bool_type)乍看起来似乎是一个指向名为bool_type的变量的指针并不容易。除了不是,给定typedef意味着最后一个词是typedef之后的所有内容。尽管它被括起来(与优先级相反)。 – SSight3