`static_cast<const bool&>` 与 `显式运算符 bool`

问题描述 投票:0回答:1

考虑以下因素:


struct C {
    explicit operator bool() const {
        return true;
    }
};

int main() {

    C c;

    auto b = static_cast<const bool &>(c);

    return 0;

}

Clang++ 18 编译良好,G++ 14 说:

test.cpp: In function ‘int main()’:
test.cpp:12:14: error: invalid ‘static_cast’ from type ‘C’ to type ‘const bool&’
   12 |     auto b = static_cast<const bool &>(c);
      |              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

请参阅编译器资源管理器

我的代码中出现了这种不兼容性,因为 Catch2 测试宏在底层使用了这种

static_cast
,并且使用带有
explicit operator bool
的自定义类型会失败,但仅限于 G++。

在我看来,由于

bool
临时对象可以绑定到
const bool &
,因此应该允许这样做。

谁在这里遵循标准?

c++ g++ language-lawyer clang++
1个回答
0
投票

该程序是格式错误,因为这里没有允许

const bool& t(c);
的隐式转换序列。

这可以从expr.static.cast#4看出:

如果存在从 E 到 T 的隐式转换序列 ([over.best.ics]),如果直接初始化 ([dcl.init]) 的重载决策,则表达式 E 可以显式转换为类型 T来自 E 的类型 T 的对象或引用将找到至少一个可行函数 ([over.match.viable]),或者如果 T 是具有第一个元素 x 的聚合类型 ([dcl.init.aggr]),并且存在是从 E 到 x 类型的隐式转换序列。 如果T是引用类型,则效果与执行声明和初始化相同

T t(E);

基本上,由于同样的原因,这是格式错误的

 const bool &ref (c);
格式错误。

请注意,clang 也接受

 const bool &ref (c);
,而所有其他 3 个编译器都正确拒绝它。 演示

© www.soinside.com 2019 - 2024. All rights reserved.