我刚刚尝试使用explicit operator bool()
第一次,它的行为对我来说是非常意外的。有人可以请说明为什么以下部分标有// does not work
。明确布尔操作符 - 不能返回,测试,初始化布尔
该convertible
类将例如,是一个智能指针类,能够检查包含数据的有效性。
struct convertible
{
explicit operator bool() const
{
return ptr;
}
void* ptr = nullptr;
};
bool testReturn()
{
convertible test;
// does not work
return test;
}
bool testReturn2()
{
convertible test;
// does not work
return test == true;
}
bool testReturn3()
{
convertible test;
// works ?!
return !test;
}
int main()
{
convertible test;
// works
if (test) { }
// works
bool init(test);
bool tested = test;
bool tested2 = testReturn();
bool tested3 = testReturn2();
bool tested4 = testReturn3();
return 0;
}
GCC的,我得到:
[email protected]:/tmp$ g++ --version
g++ (GCC) 4.8.2 20131219 (prerelease)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
[email protected]:/tmp$ g++ -std=c++11 test.cpp
test.cpp: In function ‘bool testReturn()’:
test.cpp:15:10: error: cannot convert ‘convertible’ to ‘bool’ in return
return test;
^
test.cpp: In function ‘bool testReturn2()’:
test.cpp:22:15: error: no match for ‘operator==’ (operand types are ‘convertible’ and ‘bool’)
return test == true;
^
test.cpp:22:15: note: candidate is:
test.cpp:22:15: note: operator==(int, int) <built-in>
test.cpp:22:15: note: no known conversion for argument 1 from ‘convertible’ to ‘int’
test.cpp: In function ‘int main()’:
test.cpp:39:17: error: cannot convert ‘convertible’ to ‘bool’ in initialization
bool tested = test;
铿锵它类似于:
[email protected]:/tmp$ clang++ --version
clang version 3.4 (tags/RELEASE_34/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
[email protected]:/tmp$ clang++ -std=c++11 test.cpp
test.cpp:15:10: error: no viable conversion from 'convertible' to 'bool'
return test;
^~~~
test.cpp:22:15: error: invalid operands to binary expression ('convertible' and 'int')
return test == true;
~~~~^~~~~
test.cpp:39:8: error: no viable conversion from 'convertible' to 'bool'
bool tested = test;
^ ~~~~
3 errors generated.
太棒了 - 这正是我想要的!但奇怪的是,这仍然无法按预期工作:'foo f; f == true;'它显然试图在这里用int来转换? – milianw
@milianw第一:不要写像'if(f == true)'这样的复合词。只要写'if(f)'。 '== true'是多余的。 BTW'true'和'false'关键字被定义为整数?大声笑。只是不要写'==真正' – Manu343726
@milianw [我发布了一个关于该主题的问题](http://stackoverflow.com/questions/21351450/implicit-conversion-to-boolean-and-comparison-with-布尔文字)。看起来像布尔比较被提升为积分比较,所以在用户定义的转换与布尔比较的情况下,请求整数转换。 – Manu343726