有一个更早的问题(8年前!)关于模板和鸭子输入之间的关系,在这里:C++模板和鸭子类型之间有什么关系?,我借用并修改了关于C++的一个新特性的标签行。
随着C++20的出现,“概念”的新特性看起来更像鸭子类型的特性。新的C++“概念”等同于C++的鸭子类型,这是正确的吗?如果没有,又有什么不同呢?
发布于 2019-11-06 21:14:11
随着C++20的出现,“概念”的新特性看起来更像鸭子类型的特性。
不怎么有意思。
- I disagree with both the accepted answer on the linked question and the Wikipedia page, because doing _the same thing_ at compile time instead of run time is not a persuasive reason to give it a wholly different name. See static vs. dynamic polymorphism for example.
- then concepts are not obviously more duck-type-y than templates already are
- the other argument here is that duck typing generally supposes you express your type constraints by _attempting to use the type_. Concepts are further from this model than templates already are.
- the reason templates are not (an example of) duck typing is that they happen at compile time
- concepts also happen at compile time
- QED
概念采用模板已经做的事情(可能是,也可能不是,但肯定是鸭类型),并为专门化提供更细粒度的选项,和/或更清楚地表示类型约束,并且(希望)帮助生成更好的错误。
在所有这些操作下,鸭子的质量是不变的。
发布于 2019-11-06 20:52:06
这完全取决于您如何定义“鸭子类型”。
如果您使用字典定义 (“如果它走路像鸭子,它像鸭子一样嘎嘎叫,那么它一定是鸭子”),那么预概念模板是鸭子类型的一种形式。。
模板不是鸭子类型本质上是一个术语常用方式的论证:据说使用“鸭子类型”(Python等)的语言在运行时完成了对鸭子实际上是鸭子的大部分/全部验证。模板在编译时执行它们的等效操作,因此它们不表示鸭子类型。
请注意,概念并不影响这两种解释。如果您认为运行时检查是“鸭子类型”本质的一个基本部分,那么即使有概念,模板也不是鸭子类型。
因此,如果您觉得模板是鸭类型的预概念,那么您可能会有相同的感觉后概念。反之亦然。
https://stackoverflow.com/questions/58737419
复制相似问题