显式转换运算符bool(Explicit conversion operator bool)

编程入门 行业动态 更新时间:2024-10-26 16:23:00
显式转换运算符bool(Explicit conversion operator bool)

我有以下代码

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 constructor

I 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

更多推荐

本文发布于:2023-07-27 17:55:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   bool   Explicit   conversion   operator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!