The Safe Bool Idiom by Bjorn Karlsson
Foo라는 클래스가 있을 때,
Foo f; using namespace std; class SafeBoolIdiom // Function address can’t be compared using ‘<' or '>‘. public: operator bool_type() const // The following two operator overloadings prevent template void dump(SafeBoolIdiom b)
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::tr1;
{
bool ok_;
typedef void (SafeBoolIdiom::*bool_type)() const;
// But, they’re still can be compared using ‘==’ or ‘!=’.
void this_type_does_not_support_comparisons() const { }
explicit SafeBoolIdiom(bool b=true):ok_(b) { }
{
return ok_ == true ?
&SafeBoolIdiom::this_type_does_not_support_comparisons : 0;
}
};
// 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;
}
bool operator==(const SafeBoolIdiom& lhs, const T&)
{
lhs.this_type_does_not_support_comparisons();
return false;
}
{
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]