c++ - 奇怪的 bool 重载

标签 c++

你能为我解释一下这里的 typedef 是做什么的以及目的是什么吗?

class C
{
    public:
        ...

        typedef bool (C::*implementation_defined_bool_type)(bool) const;

        operator implementation_defined_bool_type() const {
            return _spi ? &C::isPersistent : 0;
        }

};

最佳答案

Can you explain for me what the typedef is doing here?

typedef bool (C::*implementation_defined_bool_type)(bool) const;

typedef是一个C类型的指向常量成员函数的指针,它接受一个bool作为输入参数并返回一个 bool

同时,

operator implementation_defined_bool_type() const 

接收C类型的对象并返回implementation_define_bool_type类型。
它被称为转换运算符

what is the purpose of it?

它实现了“Safe Bool Idiom”,旨在验证 bool 上下文中的对象。
请注意 Safe Bool Idiom is obsolete符合 C++11 标准。

好读:
The Safe Bool Idiom

关于c++ - 奇怪的 bool 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11098971/

相关文章:

c++ - std::future 是否旋转等待?

C++ 输入验证打印两次?

c++ - 新手 : Minimal program to display a PNG in a window

c++ - 使用 2 个 char[] 指针列表初始化一个 vector<string>

c++ - C++中的线程间通信

c++ - 取消分配继承,C++

java - 在 c++/python/java 中内置抽象数据类型

c++ - C++ 中的语句 new employee *[num] 是什么意思

c++ - log 和 rand() 给出的不是数字

c++ - apply_visitor 不改变对象