branch什么意思中文翻译_Ad-hoc多态是什么?

f76799ec6adfae277cd0851d860b5486.png

最近在读《Rust编程之道》,里面提到多态时讲到了三种多态形式: 参数化多态(Parametric polymorphism)、Ad-hoc多态(Ad-hoc polymorphism) 和子类型多态(Subtype polymorphism)。这里介绍一下其中的Ad-hoc多态是什么?

Ad-hoc的字面意思

Ad-hoc在wiki上的中文翻译是特设多态,不过似乎很少又中文书籍会这样翻译,目前见到的书籍里几乎都保留了原文,所以Ad-hoc其实一直比较令人迷惑,不理解含义(难道是因为我六级没过)。后来看到了wiki上的解释如下:

Ad hoc是一个拉丁文常用短语。这个短语的意思是“特设的、特定目的的(地)、即席的、临时的、将就的、专案的”。这个短语通常用来形容一些特殊的、不能用于其它方面的,为一个特定的问题、任务而专门设定的解决方案。

Ad-hoc polymorphism源自于哪里?

Ad-hoc polymorphism 一词来源于一篇名为《Fundamental Concepts in Programming Languages》的论文,该文于1967年8月由Christopher Strachey在哥本哈根的计算机程序设计暑期学校发表,其中还首次提出了参数多态,左值和右值等概念。

Ad-hoc polymorphism是什么意思?

根据Types and Programming Languages的提到的

Parametric polymorphism (...), allows a single piece of code to be typed “generically,” using variables in place of actual types, and then instantiated with particular types as needed. Parametric definitions are uniform: all of their instances behave the same. (...)
Ad-hoc polymorphism, by contrast, allows a polymorphic value to exhibit different behaviors when “viewed” at different types. The most common example of ad-hoc polymorphism is overloading, which associates a single function symbol with many implementations; the compiler (or the runtime system, depending on whether overloading resolution is static or dynamic) chooses an appropriate implementation for each application of the function, based on the types of the arguments.

参数化多态(Parametric polymorphism)是指一段代码适用于不同的类型,把类型作为参数,在实际需要的时候根据类型进行实例化,所有的实例有相同的行为。有过C++模板编程经验的同学的同学应该很熟悉这种场景,比如下面的代码:

template <typename T> T Add(T a, T b)
{
    return a + b;
}

而 Ad-hoc polymorphoism则与之相对,是指不同的类型表现出不同的行为,同样,C++里的函数重载就是一个很典型的例子,比如operator+操作,针对字符串的重载可以是拼接,而针对整数的重载是求和。函数重载是编译器的多态,也被称作静态作态,而我们面向对象中经常提到的多态则是运行时多态,同样的,这种运行时多态也属于Ad-hoc polymorphoism。

感谢@jihao1234567补充,Rust里没有函数重载,操作符的重载是由trait来实现的。

写的不对或者不好的地方欢迎批评指正!

引用

https://zh.wikipedia.org/wiki/%E7%89%B9%E8%AE%BE%E5%A4%9A%E6%80%81​zh.wikipedia.org https://zh.wikipedia.org/wiki/Ad_hoc​zh.wikipedia.org
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值