开发者

Why base class is not automatically deduced in the same "auto" declaration?

开发者 https://www.devze.com 2023-03-17 06:57 出处:网络
Below error related to auto, is understandable: auto i = int(), d = double(); // error: inconsistent deduction for ‘auto’

Below error related to auto, is understandable:

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

However, why following is victimized with the same error:

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

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

Having known that, b1 is already deduced to const B&, can't compiler try making b2 als开发者_StackOverflow社区o a const B& ? (i.e. What kind of hazard it can cause if b2 would have been deduced to const B& ?)


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.


No. The compiler doesn't have that freedom. All auto variables, that fall in same declaration, must be of same type.

Answer this. Why can't compiler call float version of this:

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

f(10.5);

Because, compiler doesn't have that freedom to automatically deduce the proper function, when there is ambiguity involved.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号