我有以下代码
class C { public: C(bool v_):v(v_){}; explicit operator bool() const {return v;} bool v = false; }; int main(){ C a{true}; C b{false}; // C d = true; // doesn't compile, since requires explicit conversion C d = static_cast<bool>(true); // fine if(a || b) std::cout << "conversion happened!" << std::endl; // why it doesn't require explicit conversion here? }它输出“转换发生!”。 我的问题是为什么|| 被认为是一个明确的转换?
编辑
// C d = true; // actually this line compiles because of the constructorI have the following code
class C { public: C(bool v_):v(v_){}; explicit operator bool() const {return v;} bool v = false; }; int main(){ C a{true}; C b{false}; // C d = true; // doesn't compile, since requires explicit conversion C d = static_cast<bool>(true); // fine if(a || b) std::cout << "conversion happened!" << std::endl; // why it doesn't require explicit conversion here? }It outputs "conversion happened!". My question is why || is considered to be a explicit conversion?
Edit
// C d = true; // actually this line compiles because of the constructor最满意答案
来自[expr.log.or]:
操作数都被上下文转换为bool
将上下文转换为bool可以使用显式转换。 这就是“上下文性”概念的要点:明确的转换在其有意义的时候是准许的,而不是其他的,所以你不会意外地从bool转换中形成任意的整数或指针值,但是当你实际上要求布尔,你明白了。
有关详细信息,请参见[conv] / 4:
某些语言结构要求将表达式转换为布尔值。 出现在这样的语境中的表达式e据说被上下文转换为bool ,并且当且仅当声明bool t(e); 对于一些发明的临时变量t是完美的
From [expr.log.or]:
The operands are both contextually converted to bool
Contextual conversion to bool is allowed to use explicit conversions. That's the point of the concept of "contextuality": The explicit conversion is allowed precisely when it makes sense, and not otherwise, so you don't accidentally form arbitrary integral or pointer values from the bool conversion, but when you actually ask for a bool, you get it.
See [conv]/4 for details:
Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t
更多推荐
发布评论