C++ 中编译时与运行时多态的优缺点 [英] Compile time vs run time polymorphism in C++ advantages/disadvantages

查看:28
本文介绍了C++ 中编译时与运行时多态的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++ 中,当可以使用运行时(子类、虚函数)或编译时(模板、函数重载)多态性来实现相同的功能时,为什么要选择其中一种?

In C++ when it is possible to implement the same functionality using either run time (sub classes, virtual functions) or compile time (templates, function overloading) polymorphism, why would you choose one over the other?

我认为编译时多态性的编译代码会更大(为模板类型创建更多方法/类定义),并且编译时会给你更多的灵活性,而运行时会给你更安全"的多态性(即更难被误用).

I would think that the compiled code would be larger for compile time polymorphism (more method/class definitions created for template types), and that compile time would give you more flexibility, while run time would give you "safer" polymorphism (i.e. harder to be used incorrectly by accident).

我的假设是否正确?两者还有其他优点/缺点吗?谁能举一个具体的例子,说明两者都是可行的选择,但其中一个显然是更好的选择?

Are my assumptions correct? Are there any other advantages/disadvantages to either? Can anyone give a specific example where both would be viable options but one or the other would be a clearly better choice?

此外,编译时多态性是否会产生更快的代码,因为没有必要通过 vtable 调用函数,或者这是否会被编译器优化掉?

Also, does compile time polymorphism produce faster code, since it is not necessary to call functions through vtable, or does this get optimized away by the compiler anyway?

示例:

class Base
{
  virtual void print() = 0;
}

class Derived1 : Base
{
  virtual void print()
  {
     //do something different
  }
}

class Derived2 : Base
{
  virtual void print()
  {
    //do something different
  }
}

//Run time
void print(Base o)
{
  o.print();
}

//Compile time
template<typename T>
print(T o)
{
  o.print();
}

推荐答案

静态多态产生更快的代码,主要是因为积极内联的可能性.虚拟函数很少可以内联,而且主要是在非多态"场景中.请参阅 C++ 常见问题解答 中的此项.如果速度是你的目标,你基本上别无选择.

Static polymorphism produces faster code, mostly because of the possibility of aggressive inlining. Virtual functions can rarely be inlined, and mostly in a "non-polymorphic" scenarios. See this item in C++ FAQ. If speed is your goal, you basically have no choice.

另一方面,使用静态多态不仅编译时间,而且代码的可读性和可调试性都差很多.例如:抽象方法是强制实现某些接口方法的一种干净的方式.为了使用静态多态实现相同的目标,您需要恢复到概念检查或好奇重复的模板模式.

On the other hand, not only compile times, but also the readability and debuggability of the code is much worse when using static polymorphism. For instance: abstract methods are a clean way of enforcing implementation of certain interface methods. To achieve the same goal using static polymorphism, you need to restore to concept checking or the curiously recurring template pattern.

真正必须使用动态多态的唯一情况是在编译时实现不可用;例如,当它从动态库加载时.但在实践中,您可能希望以更简洁的代码和更快的编译速度来交换性能.

The only situation when you really have to use dynamic polymorphism is when the implementation is not available at compile time; for instance, when it's loaded from a dynamic library. In practice though, you may want to exchange performance for cleaner code and faster compilation.

这篇关于C++ 中编译时与运行时多态的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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