gpt4 book ai didi

c++ - safe bool idiom bool_type(和safe bool idiom)是如何工作的?

转载 作者:行者123 更新时间:2023-11-28 01:03:22 26 4
gpt4 key购买 nike

有人指出我是“安全 bool 惯用语”,在尝试破译发生了什么之后(解释 supplied on the site 不足以让我理解为什么它有效),我决定尝试将以下代码分开并尝试尽可能地简化它。该站点提供了以下代码:

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::*',其中 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 是什么类型:

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

这表明它确实是一种'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;
}

它会产生以下投诉:

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

因此我的问题是:

如果 '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() 来避免这种丑陋。

关于c++ - safe bool idiom bool_type(和safe bool idiom)是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7704395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com