試圖找到一個「簡單易用」的safe_bool成語/實現,我已經結束了我自己的。評論:可重用的safe_bool實現
問:這個實現是否正確?
template <typename T>
class safe_bool
{
protected:
typedef void (safe_bool::*bool_type)() const;
bool_type to_bool_type(bool b) const
{ return b ? &safe_bool<T>::safe_bool_true : 0; }
private:
void safe_bool_true() const {}
private:
bool operator ==(safe_bool<T> const & rhs);
bool operator !=(safe_bool<T> const & rhs);
};
使用這樣的:
struct A : public safe_bool<A>
{
// operator bool() const { return true; }
operator bool_type() const { return to_bool_type(true); }
};
唯一除了現有的基類是to_bool_type
,但我希望我已經得到了一切正確的,太。
我使用的測試用例(VC9)can be found here。
我在實現中看到的缺點:bool_type
和to_bool_type
在派生類中可見,這可能不適用於所有人。另外,使用錯誤的模板參數(例如,在複製和粘貼期間引入的class B : public safe_bool<A>
)將不被注意。
謝謝 - 這個鏈接實際上是我開始的地方。我對他們的實施有一些懷疑,這就是爲什麼我不相信每一個iota。似乎缺少的是防止'operator ==(safe_bool)' - 但在這種情況下,這將是必要的? ----我同意複雜性與有用性評分,我的嘗試是讓它「減少傷害」。 –
peterchen
2010-01-12 19:53:24
因爲safe_bool「正常工作」,所以Downvoting尤其適用,如果您將其包裝在一個很好記錄的可重用組件中。也就是說,在C++ 11中,只需使用'explicit operator bool()const'並使用它:-) – 2011-12-11 12:28:21