Why don't iostream objects overload operator bool?

笑着哭i 提交于 2019-11-28 01:03:37
Potatoswatter

This is an instance of the "safe bool" problem.

Here is a good article: http://www.artima.com/cppsource/safebool.html .

C++0x helps the situation with explicit conversion functions, as well as the change that Kristo mentions. See also Is the safe-bool idiom obsolete in C++11? .

It looks like the C++0x standard section 27.4.4.3 has the answer (emphasis mine).

operator unspecified-bool-type() const;

Returns: If fail() then a value that will evaluate false in a boolean context; otherwise a value that will evaluate true in a boolean context. The value type returned shall not be convertible to int.

Note: This conversion can be used in contexts where a bool is expected (e.g., an if condition); however, implicit conversions (e.g., to int) that can occur with bool are not allowed, eliminating some sources of user error.

The newest C++11 requires that:

explicit operator bool() const;

See C++11 27.5.5.4-1. The 'explicit' seems odd to me, though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!