编译器如何隐式地进行这种转换

How does the compiler makes this conversion implicitly?

本文关键字:转换 何隐式 编译器      更新时间:2023-10-16

我正在观看一个来自//build的视频,其中Herb Sutter用代码片段展示了显式转换关键字的好处:

template< /* ... */ > class unique_ptr {
public:
    // ...
    explicit operator bool() const { return get() != nullptr; }

他说通过这个关键字,我们可以防止编译

use(ptr * 42); // oops, meant *(ptr) * 42

我真的看不懂,这个展柜是怎么编译的?编译器如何进行转换?到什么类型?

它隐式地从unique_ptr转换为bool,然后从bool转换为int来进行乘法。

(bool to int表示true为1,false为0)