【问题标题】:Converting C++ hierarchy to use static polymorphism将 C++ 层次结构转换为使用静态多态性
【发布时间】:2012-03-10 22:06:04
【问题描述】:

我有以下类层次结构(实际上还有更多的类),我想知道是否可以重新组织以下内容以利用静态多态性?

struct return_val {};

struct base
{
   virtual ~base(){}
   virtual return_val work(){};
};

struct derivedtype1 : public base
{
   return_val work() { return localwork(next_type.work()); }
   return_val localwork(return_val& rv0){....}
   base* next_type0;
};

struct derivedtype2 : public base
{
   return_val work() { return localwork(next_type0.work(),next_type1.work()); }
   return_val localwork(return_val& rv0, return_val& rv1){....}
   base* next_type0;
   base* next_type1;
};

struct derivedtype3 : public base
{
   return_val work() { return localwork(next_type0.work(),next_type1.work(),next_type2.work()); }
   return_val localwork(return_val& rv0, return_val& rv1, return_val& rv2){.....}
   base* next_type0;
   base* next_type1;
   base* next_type2;
};

我问,在进行了大量的分析之后,虚拟方法调用的开销实际上是相当大的,并且希望尽可能地优化它。

【问题讨论】:

  • 其实很简单:你知道编译时的最终类型吗?然后你可以使用一些静态的通用性。如果不这样做,则确实需要运行时多态性,而且没有办法。
  • @Kerrek:你可能是对的,运行时是我正在寻找的,但我希望有一个秘密的 c++ 技巧或其他东西来绕过 vf 调用的开销。
  • 这种开销实际上并不存在,它非常小,除非你有真正严格的性能要求,否则基本上不会被注意到。
  • @Xeo:对于我正在处理的当前任务而言,它很明显,开销约为总计算时间的 18%。我试图重构代码,以使 vf 调用的次数最少,所以目前 vf 开销是接下来要看的...
  • 我不确定你是如何分析你的代码以获得 18% 的数字(相对于你正在进行的 vf 调用的数量,你的计算必须做很少的工作!)无论如何,你有在诸如此类的帖子中查看答案:stackoverflow.com/questions/6599132/…

标签: c++ optimization polymorphism virtual-functions crtp


【解决方案1】:

因为你提到了 18% 的 vf 调用开销,所以我假设每个类中有很多虚函数。在这种情况下,可以试试这个:

base * pObj;
switch(pObj->getTypeIdentifier())
{
  case 1:
    static_cast<derivedtype1*>(pObj)->func1;
    static_cast<derivedtype1*>(pObj)->func2;
    ...

  case 2:
    static_cast<derivedtype2*>(pObj)->func1;
    static_cast<derivedtype2*>(pObj)->func2;
    ...
}

这基本上是虚拟调度对每个 func1、func2 等执行的操作。这里的不同之处在于,即使您访问多个函数,您也只需切换一次 - 相当于单个虚拟调度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    相关资源
    最近更新 更多