3

以下与 , 相关的错误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&不能试一下吗?(即如果推导出来会造成什么样的危害?)b2const B&b2const B&

4

2 回答 2

6

The danger would be unexpected results... when you create a D, you expect to get a D as the result. There is also the fact that there is a cast involved... it is a "safe" cast, but a cast none-the-less. An identical argument could be made for the first example... why doesn't the compiler just make d and int, since double can be converted trivially and it has already decided that is the type based on the result for i. Or what of the case where you have two sibling classes... should they both resolve to the common base?

If you want that code to compile, you can always explicitly cast the result of D() so that both expressions yield the same type.

And for the language lawyer bit:

[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.

于 2011-07-02T07:04:17.020 回答
0

不,编译器没有这种自由。属于同一声明的所有auto变量必须属于同一类型。

回答这个。为什么编译器不能调用float这个版本:

void f(int);
void f(float);

f(10.5);

因为,当涉及到歧义时,编译器没有自动推断正确函数的自由。

于 2011-07-02T07:42:24.947 回答