静态多态定义与实现

发布于 2024-10-09 14:58:15 字数 1436 浏览 3 评论 0原文

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

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

发布评论

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

评论(3

无尽的现实 2024-10-16 14:58:15
  1. 静态多态行为是发生在编译时而不是运行时的类型多态
  2. 是的。
  3. UML 是关于类如何在运行时交互的——我不相信有用于描述模板的 UML 格式,但我可能是错的。
  4. 据我所知,它是 C++ 特定的,但考虑到我没有使用过所有发明的语言,我对此并不肯定。 :) 也就是说,在某些情况下,使用运行时而不是编译时收集的信息,C# 和 Java 等 JIT 语言通常非常擅长消除间接调用对性能的影响。不管这是否是在编译时,都还没有定论……毕竟,它被称为即时编译器。
  5. 主要好处就是性能。运行时多态性可以做静态多态性可以做的所有事情(事实上它可以做更多),但它会带来间接调用的成本(如果有足够多的调用,这可能会很昂贵)

现在,模板本身除了实现编译时间之外还有很多用途多态性——例如,使 boost::bind 工作的 SFINAE 魔法当然不是多态性的——它的存在只是为了消除语言本身的不一致。

  1. Static polymorphic behavior is type polymorphism that occurs at compile time rather than run time.
  2. Yes.
  3. UML is about how classes interact at runtime -- I don't believe there's a UML format for describing templates, but I could be wrong.
  4. As far as I am aware it is C++ specific, but I'm not positive given that I've not used every language ever invented. :) That said, JIT'd languages like C# and Java often are very good at removing the performance impact of indirect calls in some cases using information gleaned at runtime rather than at compile time. Whether this is at compile time or not is kind of up on the air though... after all, it is called a Just-In-Time Compiler.
  5. The main benefit is simply performance. Runtime polymorphism can do everything static polymorphism can do (in fact it can do more), but it carries the cost of indirect calls (which can be expensive if there are enough of 'em)

Now, templates themselves have many uses beyond achieving compile time polymorphism -- for example the SFINAE magic that makes boost::bind work is certainly not polymorphic -- it's merely there in order to smooth over inconsistencies in the language itself.

眼眸里的快感 2024-10-16 14:58:15

我们如何定义静态多态性
一般情况下?

使用示例来理解它的最好方法。 基于策略的设计是静态多态性的一个示例。在我看来,这是实现静态多态性的非常强大的技术。

另一个例子是,奇怪的重复模板模式(CRTP),这也是一种强大的技术。

How do we define static polymorphism
in general?

The best way to understand it using examples. Policy Based Design is one example of static polymorphism. And in my opinion, it's very powerful technique to achieve static polymorphism.

Another example is, Curiously recurring template pattern (CRTP) which is also powerful technique.

一绘本一梦想 2024-10-16 14:58:15
  1. 不,除了模板之外,方法重载还有——静态多态。
    https://en.wikipedia.org/wiki/Function_overloading
  1. No. In addition to templates, the method oveloading is also - static polymorphism.
    https://en.wikipedia.org/wiki/Function_overloading
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文