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

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

问题描述

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 语句

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

return a * 3 + b;

您必须将程序追溯到ab 的声明点,找出类型提升,并决定返回类型.

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天全站免登陆