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

查看:24
本文介绍了类 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.

而且,天知道,C++ 重载解析就目前而言已经足够复杂了......

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

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

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