gpt4 book ai didi

c++ - 是否可以在不必派生自 safe_bool 类的情况下实现 safe bool 习语?

转载 作者:行者123 更新时间:2023-11-30 03:09:37 25 4
gpt4 key购买 nike

是否有一个技巧可以让安全的 bool 习语完全起作用,而不必从执行实际实现的类派生?

对于“完全工作”,我的意思是该类具有一个运算符,允许以安全的方式对其进行测试,就好像它是一个 boolean 值一样:

MyTestableClass a;
MyOtherTestableClass b;
//this has to work
if( a );
if( b );
//this must not compile
if( a == b );
if( a < b );
int i = a;
i += b;

例如使用此实现时

struct safe_bool_thing
{
int b;
};
typedef int safe_bool_thing::* bool_type;
safe_bool( const bool b ) { return b ? &safe_bool_thing::b : 0; }

class MyTestableClass
{
operator bool_type () const { return safe_bool( someCondition ); }
}

几乎没问题,除了 a == b 仍然可以编译,因为可以比较成员指针。与上面相同的实现,但使用指向成员函数的指针而不是指向成员变量的指针具有完全相同的问题。

已知的完美运行的实现(例如 here 或 boost 中使用的 safe_bool)要求可测试类派生自提供实际运算符实现的类。

我实际上认为没有办法解决它,但不完全确定。我尝试了一些看起来有点 fischy 的东西,但我认为它可能有用,但根本无法编译。为什么不允许编译器看到运算符返回一个 safe_bool_thing,而后者又可以转换为 bool() 并因此被测试?

struct safe_bool_thing
{
explicit safe_bool_thing( const bool bVal ) : b( bVal ) {}
operator bool () const { return b; }
private:
const bool b;
safe_bool_thing& operator = ( const safe_bool_thing& );
bool operator == ( const safe_bool_thing& );
bool operator != ( const safe_bool_thing& );
};

class MyTestableClass
{
operator safe_bool_thing () const { return safe_bool_thing( someCondition ); }
};

MyTestableClass a;
if( a ); //conditional expression of type 'MyTestableClass' is illegal

最佳答案

这应该有效:

class MyTestableClass
{
private:
void non_comparable_type() {}
public:
typedef void (MyTestableClass::* bool_type)();

operator bool_type () const { return (someCondition ? &MyTestableClass::non_comparable_type : 0); }
};

class MyOtherTestableClass
{
private:
void non_comparable_type() {}
public:
typedef void (MyOtherTestableClass::* bool_type)();

operator bool_type () const { return (someCondition ? &MyOtherTestableClass::non_comparable_type : 0); }
};

要阻止 if (a == b) 情况,这取决于两种类型都转换为不兼容的指针类型这一事实。

关于c++ - 是否可以在不必派生自 safe_bool 类的情况下实现 safe bool 习语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940908/

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