不同编程语言中的重载

发布于 2024-10-11 06:08:25 字数 39 浏览 4 评论 0原文

有人可以解释(举例)上下文无关重载和上下文相关重载之间的区别吗?

Can somebody please explain (with example) the difference between context-independent and context-dependent overloading?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谈下烟灰 2024-10-18 06:08:25

我从来没有听说过这些。谷歌上只有大约五次点击,其中之一就是这个问题,这似乎表明这些都是虚构的术语。与任何虚构的术语一样,如果你想知道它的含义,你必须询问创造它的人。

据我所知,它似乎与基于返回类型的重载有关。

基本上,如果您有四个像这样的重载函数:

foo :: string → int
foo :: string → string
foo :: string → ()
foo :: int → int

这样调用它们:

1 + foo 1
1 + foo "one"
foo "one"

然后,使用上下文相关的重载(即基于返回类型和参数类型的重载),将选择以下实现:

1 + foo 1     # foo :: int → int
1 + foo "one" # foo :: string → int (because `+` takes an `int`)
foo "one"     # foo :: string → ()  (because there is no return value)

并且您 与上下文无关的重载(即忽略返回类型),将选择以下实现:

1 + foo 1     # foo :: int → int
1 + foo "one" # ERROR
foo "one"     # ERROR

在两种 ERROR 情况下,foo :: string → int 之间存在歧义、 foo :: string → stringfoo :: string → (),因为它们仅在返回类型上有所不同,但具有相同的参数类型。

I have never heard about those. And there's only about five hits on Google, one of which is this very question, which seems to suggest to me that these are made-up terms. And as with any made-up term, if you want to know what it means, you have to ask the person who made it up.

From what little I could gather, it seems to be related to return-type based overloading.

Basically, if you have four overloaded functions like these:

foo :: string → int
foo :: string → string
foo :: string → ()
foo :: int → int

And you call them like this:

1 + foo 1
1 + foo "one"
foo "one"

Then, with context-dependent overloading (i.e. overloading based on the return type as well as the parameter types), the following implementations will be selected:

1 + foo 1     # foo :: int → int
1 + foo "one" # foo :: string → int (because `+` takes an `int`)
foo "one"     # foo :: string → ()  (because there is no return value)

Whereas with context-independent overloading (i.e. ignoring the return type), the following implementations will be selected:

1 + foo 1     # foo :: int → int
1 + foo "one" # ERROR
foo "one"     # ERROR

In both the ERROR cases, there is an ambiguity between foo :: string → int, foo :: string → string and foo :: string → (), since they only differ in their return type but have the same paremeter type.

小镇女孩 2024-10-18 06:08:25

引用自此处

重载有两种
函数/运算符。

  • 与上下文无关 - 仅对参数进行重载
    函数或操作数类型
    运算符
  • 上下文相关 - 调用哪个抽象也取决于
    结果的类型

Quoting from here:

There are two kinds of overloading of
functions/operators.

  • context-independent - overloading only done on parameters to
    function or type of operands for an
    operator
  • context-dependent - which abstraction to call also depends upon
    the type of the result
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文