类C语言中的返回类型多态 [英] Return type polymorphism in C-like languages

查看:156
本文介绍了类C语言中的返回类型多态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们没有看到类似C的语言,允许在返回类型中具有多态性的可调用对象?我可以看到附加的类型推断将是一个障碍,但是我们有大量的语言与完善的类型推断系统(可用于不同级别的工作").

Why don't we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we have plenty of languages with full-fledged type inference systems (that work for varying levels of "work").

通过返回类型多态性,我的意思是仅在返回类型中重载函数签名.例如,C ++和Java仅允许在形式参数的类型中重载,而不能在返回类型中重载.

By return type polymorphism I mean overloading the function signature only in the return type. For example, C++ and Java only allow overloading in the type of the formal parameters, not in the return type.

推荐答案

如果通过返回类型多态性"表示基于返回值类型的重载,我不确定其他语言,但是对于C ++,这是答案(几乎是从马口传来的):

If by "return type polymorphism" you mean overloading based on the return value type, I'm not sure about other languages, but for C++ here's the answer (pretty much from the horse's mouth):

函数返回类型不会在重载解析中起作用,仅仅是因为Stroustrup(我假设其他C ++架构师的输入)希望重载解析是上下文无关的".请参见"C ++编程语言,第三版"中的7.4.1-重载和返回类型".

Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition".

原因是要保持分辨率 单个运算符或功能 称为上下文无关.

The reason is to keep resolution for an individual operator or function call context-independent.

他们希望它仅基于调用重载的方式,而不是基于结果的使用方式(如果完全使用了结果).实际上,在不使用结果的情况下调用了许多函数,或者将结果用作较大表达式的一部分.我确定他们决定这样做的一个因素是,如果返回类型是解决方案的一部分,那么将会有很多对重载函数的调用,这些调用需要使用复杂的规则来解决,或者必须让编译器抛出通话不明确的错误.

They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all). Indeed, many functions are called without using the result or the result would be used as part of a larger expression. One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.

Lord知道,C ++重载解析就其本身而言已经足够复杂了...

And, Lord knows, C++ overload resolution is complex enough as it stands...

这篇关于类C语言中的返回类型多态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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