gpt4 book ai didi

c++ - 为什么在同一个 "auto"声明中不自动推导基类?

转载 作者:太空狗 更新时间:2023-10-29 20:30:35 27 4
gpt4 key购买 nike

以下与auto 相关的错误是可以理解的:

auto i = int(), d = double(); // error: inconsistent deduction for ‘auto’

但是,为什么下面会出现同样的错误:

struct B {};
struct D : B {};

const auto &b1 = B(), &b2 = D(); // error: inconsistent deduction for ‘auto’

既然已经知道,b1 已经推导为 const B&,编译器就不能尝试让 b2 也成为 const B& ? (即,如果 b2 被推断为 const B& 会导致什么样的危险?)

最佳答案

危险会是意想不到的结果……当你创造一个 D 时,你期望得到一个 D 作为结果。还有一个事实是涉及类型转换……这是一个“安全”类型转换,但仍然是类型转换。可以为第一个示例提出相同的论点...为什么编译器不只生成 dint,因为 double 可以是转换很简单,它已经根据 i 的结果确定了类型。或者如果您有两个同级类...它们应该都解析为公共(public)基类吗?

如果您希望该代码能够编译,您始终可以显式转换 D() 的结果,以便两个表达式产生相同的类型。

对于语言律师位:

[decl.spec.auto]/7:

If the list of declarators contains more than one declarator, the type of each declared variable is determined as described above. If the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.

关于c++ - 为什么在同一个 "auto"声明中不自动推导基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555515/

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