我回答this question,有關用戶定義的轉換到bool
以及如何的話題比較禁用其他轉換:隱式轉換爲布爾值,並與布爾文字
struct foo
{
operator bool() const //Explicit overload for bool
{
return true;
}
template<typename T>
operator T() const = delete; //Everithing which is not a bool (Everithing which
//does not fit in the explicit overload) would
//resolve to this operator and will fail.
};
int main()
{
foo f;
bool b = f; //OK
int i = f; //ERROR
char c = f; //ERROR
etc...
}
後來,OP問我爲什麼喜歡if(f == true)
條件語句失敗(凡f
是foo
我試圖通過我自己和我吃驚,因爲與布爾文字是比較導致轉換到int
(這是禁用的),而不是bool
:
int main()
{
foo f;
if(f); //OK, converts to bool
if(f == true); //ERROR: Conversion to int, which has been disabled
}
prog.cpp:20:12: error: use of deleted function ‘foo::operator T() const [with T = int]’ if(f == true);
..............................................................................................................................................^
我的問題是:是布爾文字定義爲整數(如常見的C宏#define true 1 #define false 0
),如果沒有,爲什麼比較鉛爲int的轉換,而不是bool
?
我在啓用C++ 11的情況下使用GCC4.8.1(-std=C++11
)。
Here是ideone行爲的一個例子。
注有一個在之間的相關例子的有趣差異並[g ++ 4.8.1](HTTP://coliru.stacked- [CWG 954](http:// www。com/cn/b2865b8fea3021b4)和[clang ++ 3.5](http://coliru.stacked-crooked.com/a/cc3c7a74ee58d588) – dyp
這可能是標準中的缺陷, //www.open-std.org/JTC1/SC22/WG21/docs/cwg_active.html#954)(open issue),特別是註釋*「有些實現明確地選擇了int類型候選。被調整來選擇L和R是相同類型的候選人?「*(這是我答案中缺失的部分) – dyp