模板类和可能的性能问题

时间:2013-03-18 10:51:15

标签: c++ metaprogramming template-classes

如果我使用模板类来创建30个不同的定义。我的问题是它是否会以二进制编译成30个实际类(二进制大小= sizeof(template_class)x 30),尽管它们的实际代码非常相似甚至完全相同?

如果它会,并且在运行时,我的程序将加载到内存中。我循环遍历这30个实例(假设我为每个定义初始化了1个实例),是否会导致cpu指令缓存重新加载,因为它们实际上是30个内存副本,甚至大多数代码都是相同的?

    template<typename msg_policy, int id>
    class temp_class_test : public msg_policy
            //codes, methods, and members
    };

    template class temp_class_test<A_policy,1>;
    template class temp_class_test<B_policy, 2>;

3 个答案:

答案 0 :(得分:2)

就目前而言,从模板中实例化的类是具有不同代码的不同类。是的,这会导致代码在执行时一次又一次地重新加载。

您可以按照Walter在评论中建议的方式缓解这种情况:将实现放在一些所有其他类派生的公共基类中。我详细介绍了这项技术in my answer on the question on “How to define different types for the same class in C++”

答案 1 :(得分:2)

如果您的30多个类非常相似,则应避免代码重复。例如,模板参数id可能只是一个存根来区分其他相同的类。在这种情况下,您不需要为每个id重新定义类,但可能只是从实现继承:

namespace implementation {
  template<typename p> class test {
    // implementation
  };
}
template<typename p, int id>
class temp_class_test : public implementation::test<p>
{
   // any additional code dependent on id
   // any non-inheritable code (constructors)
};

编译器只会为基类的每个方法生成一个二进制文件,id仅用于区分不同的temp_class_test

答案 2 :(得分:0)

完成尸检。这就是为什么当我的应用程序处于压力之下时我的应用程序表现如此糟糕这是因为我的cpu经历了永远缓存错过。