xml*_*lmx 7 c++ iostream type-conversion explicit-conversion c++11
我检查了C++ 11标准,发现了以下事实:
std::getline(fin, str)返回一个basic_ios对象,其类具有成员函数explicit operator bool() const;
该类basic_ios没有成员函数operator void*() const;作为pre-C++ 11.
所以,我认为if (getline(fin, str)) {}不符合标准.它应该写成
if (bool(getline(fin, str)){}.(但是,VC++ 2012会对此用法发出警告.即强制void*为bool)
我对么?
explicit operator bool(并且仅 explicit operator bool)具有允许bool在某些情况下隐式转换为a的特殊语言.此转换的规范语言是"上下文转换为bool".
这些是语言进行布尔测试的地方.a使用的条件表达式if/while/for是"上下文转换为bool".与逻辑运算符和条件运算符(?:)一样.
所以,虽然你不能这样做:
bool b = std::getline(fin, str);
void func(bool) {}
func(std::getline(fin, str));
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
while(std::getline(fin, str)) {...}
for(;std::getline(fin, str);) {...}
if(std::getline(fin, str) && somethingElse) {...}
Run Code Online (Sandbox Code Playgroud)
大卫是对的,这是支持他的报价.§12.3.2/ 2,标准说
转换函数可以是显式的(7.1.2),在这种情况下,它仅被视为直接初始化(8.5)的用户定义转换.否则,用户定义的转换不限于在分配和初始化中使用.[ 例如:
Run Code Online (Sandbox Code Playgroud)class Y { }; struct Z { explicit operator Y() const; }; void h(Z z) { Y y1(z); // OK: direct-initialization Y y2 = z; // ill-formed: copy-initialization Y y3 = (Y)z; // OK: cast notation }- 结束例子 ]
发生这种上下文转换的一些地方是操作数!,操作数&&和一个条件if.
因此,直接初始化可以使用显式转换运算符,在§4/ 3中,
对于某些发明的临时变量t(8.5),
T当且仅当声明T t=e;格式正确时,表达式e才能隐式转换为类型.某些语言结构要求将表达式转换为布尔值.在这样的上下文中出现的表达式e被称为在上下文中被转换为bool并且当且仅当声明bool t(e);格式良好时,对于一些发明的临时变量t(8.5)...
正如您所看到的,该标准指定了上下文转换的直接初始化,这就是为什么显式转换在if条件下工作的原因.