The Safe Bool Idiom

Tags:

The Safe Bool Idiom by Bjorn Karlsson

Foo라는 클래스가 있을 때,

Foo f;
if (f) cout << "true" << endl; [/code] 는 허용하되, f == f2 나 f != f2나 f < f2나 int i = f 를 다 막는 방법. std::tr1::shared_ptr 에 operator unspecified_bool_type() const가 같은 기법을 사용하고 있습니다. [code lang="cpp"] #include
#include

using namespace std;
using namespace std::tr1;

class SafeBoolIdiom
{
bool ok_;
typedef void (SafeBoolIdiom::*bool_type)() const;

// Function address can’t be compared using ‘<' or '>‘.
// But, they’re still can be compared using ‘==’ or ‘!=’.
void this_type_does_not_support_comparisons() const { }

public:
explicit SafeBoolIdiom(bool b=true):ok_(b) { }

operator bool_type() const
{
return ok_ == true ?
&SafeBoolIdiom::this_type_does_not_support_comparisons : 0;
}
};

// The following two operator overloadings prevent
// the use of ‘==’ and ‘!=’.
template
bool operator!=(const SafeBoolIdiom& lhs, const T&)
{
// Look. This will raise compile time error,
// because the method being called is private.
lhs.this_type_does_not_support_comparisons();
return false;
}

template
bool operator==(const SafeBoolIdiom& lhs, const T&)
{
lhs.this_type_does_not_support_comparisons();
return false;
}

void dump(SafeBoolIdiom b)
{
if (b) // Oh Ma sweet bool!
cout << "true" << endl; else cout << "false" << endl; } int main() { SafeBoolIdiom b(true); SafeBoolIdiom b2(false); dump(b); dump(b2); return EXIT_SUCCESS; } [/code]