为什么虚函数不能使用返回类型的扣除? [英] Why can't virtual functions use return type deduction?

查看:197
本文介绍了为什么虚函数不能使用返回类型的扣除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

n3797 说:

§7.1.6.4/14:

§ 7.1.6.4/14:


用返回类型声明的函数,
不能是虚拟的(10.3)。

A function declared with a return type that uses a placeholder type shall not be virtual (10.3).

因此,下面的程序是错误的:

Therefore the following program is ill-formed:

struct s
{
    virtual auto foo()
    {
    }
};

我可以找到的理由是这个模糊的一行从n3638

All I can find for the rationale is this vague one-liner from n3638:


虚拟

这可能允许虚拟
函数的返回类型扣除,重写检查和vtable
布局,所以似乎更好禁止这个。

It would be possible to allow return type deduction for virtual functions, but that would complicate both override checking and vtable layout, so it seems preferable to prohibit this.

任何人都可以提供进一步的理由或给一个好的

Can anyone provide further rationale or give a good (code) example that agrees with the above quote?

推荐答案

包含的理由是相当清楚的:自然地,虚函数意味着被子类覆盖,所以你作为基类的设计者应该尽可能地让继承你的类的人提供一个合适的覆盖。但是,如果使用 auto ,找出覆盖的返回类型对于程序员来说是一个乏味的任务。

The rationale that you included is reasonably clear: naturally, virtual functions are meant to be overridden by subclasses, so you as the designer of the base class should make it as easy as possible for people who inherit your class to provide a suitable override. However, if you use auto, figuring out the return type for the override becomes a tedious task for a programmer. Compilers would have less of a problem with it, but humans would have many opportunities to get confused.

例如,如果你看到一个看起来像这样的return语句, p>

For example, if you see a return statement that looks like this

return a * 3 + b;

您必须将程序追溯到 a b ,找出类型促销,并决定返回类型。

you would have to trace the program back to the point of declaration of a and b, figure out the type promotions, and decide what the return type shall be.

看来,语言设计师认为这将是相当混乱,并决定不允许此功能。

It appears that the language designers figured out that this would be rather confusing, and decided against allowing this feature.

这篇关于为什么虚函数不能使用返回类型的扣除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆