gpt4 book ai didi

C++ safe boolean idiom 不能用 Visual C++ 10(2010) 编译

转载 作者:太空宇宙 更新时间:2023-11-04 12:22:03 26 4
gpt4 key购买 nike

嘿伙计们,我从这个页面的 C++ safe bool idiom 类派生了我的类:The Safe Bool Idiom by Bjorn Karlsson

class Element : public safe_bool<>
{
public:
bool Exists() const;
// boolean_test() is a safe_bool method
bool boolean_test() const { return Exists(); };
};

当我尝试在下面的 if 表达式中使用它时

Element ele;
...
if(ele)

我遇到了一个错误 C2451:“元素”类型的条件表达式是非法的。如果我尝试将其转换为如下所示的 bool 值,则会出现此错误

Element ele;
...
if((bool)ele)

错误 C2440:“类型转换”:无法从“元素”转换为“ bool ”

这是我第一次使用安全 bool 惯用语,我不确定这是不允许的还是 Visual C++ 10 中的错误。有什么意见吗?提前致谢!

最佳答案

安全的 bool 习语是允许的,尽管我通常这样写:

class Element
{
public:
bool Exists() const;

/* Begin Safe Bool Idiom */

private:
// This is a typedef for pointer to an int member of Element.
typedef int Element::*SafeBoolType;
public:
inline operator SafeBoolType() const
{ return Exists() ? &Element::someDataMember : 0; }
inline bool operator!() const
{ return !Exists(); }

/* End Safe Bool Idiom */

private:
int someDataMember; // Pick any data member
// ...
};

这就是我看到它的实现方式。事实上,Boost 以这种方式为智能指针类 ( using an include file ) 实现了惯用法。

关于C++ safe boolean idiom 不能用 Visual C++ 10(2010) 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4438929/

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