gpt4 book ai didi

c++ - 显式转换运算符和常量引用限定

转载 作者:行者123 更新时间:2023-12-03 23:40:37 25 4
gpt4 key购买 nike

以下示例在 godbolt 上编译良好与 -std=c++17使用 clang,但使用 msvc 和 gcc 失败:

struct Foo
{
};

struct Bar
{
explicit operator Foo() // w/o explicit qualification all are happy
{
return Foo();
}
};

int main()
{
Bar b;
const Foo& foo = static_cast<const Foo&>(b); // only clang happy with this
const Foo& foo2 = static_cast<const Foo&>(static_cast<Foo>(b)); // clang / msvc / gcc happy with this
return 0;
}
据我了解 explicit对运算符干脆禁止 implicit conversions ,并且由于页面列出了它们之间的资格转换,我认为在这种情况下clang是完全错误的?还是我错过了什么?
理想情况下,我希望坚持使用单次转换,因为我在模板代码中使用它,如果 const-reference 转换运算符可用,则使用它。但我也可以放弃 explicit约束。

最佳答案

OP 的例子并不是非常少。一个真正最小的示例使用,而不是 static_cast然后是初始化,简单地说:

const Foo& foo(b);
这就是 static_cast<const Foo&>(b)无论如何,应该这样做。
再次,Clang 接受而 GCC 拒绝 [ godbolt ]。如果将其更改为复制初始化 ( const Foo& foo = b;),则 Clang 和 GCC 都会拒绝。
似乎 Clang 是正确的:在直接初始化的情况下,为什么不应该 explicit转换函数可以用吗?
该问题被标记为 c++11,因此请参阅 C++11 [over.match.ref]/1:

Under the conditions specified in 8.5.3, a reference can be bound directly to a glvalue or class prvalue that is the result of applying a conversion function to an initializer expression. Overload resolution is used to select the conversion function to be invoked. Assuming that “cv1 T” is the underlying type of the reference being initialized, and “cv S” is the type of the initializer expression, with S a class type, the candidate functions are selected as follows:

  • The conversion functions of S and its base classes are considered, except that for copy-initialization, only the non-explicit conversion functions are considered. Those that are not hidden within S and yield type “lvalue reference to cv2 T2” (when 8.5.3 requires an lvalue result) or “cv2 T2” or “rvalue reference to cv2 T2” (when 8.5.3 requires an rvalue result), where “cv1 T” is reference-compatible (8.5.3) with “cv2 T2”, are candidate functions.

8.5.3 中的措辞是 defect report 的主题。这在 C++14 中已解决,以澄清引用绑定(bind)不使用“隐式转换”,而是使用“转换”(其中 [over.match.ref] 仅在复制初始化中排除 explicit 函数案子)。该决议应被视为可追溯至 C++11。
标准的每个版本的措辞都有所变化,但我认为结论是相同的。
我查找了有关此问题的现有 GCC 错误报告,但令人惊讶的是找不到。我认为打开一个错误报告是个好主意,如果 GCC 开发人员坚持认为 GCC 是正确的,他们会解释他们为什么这么认为。

关于c++ - 显式转换运算符和常量引用限定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66016386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com