我回答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