简体   繁体   中英

C++ dynamic template creation

I've got a template class with an integer parameter, but I only know the template parameter at runtime. Is there any best practice to create template classes at runtime?

The solution I've come up with is to create an abstract base class of the template class, that provides the interface and have an adapter class, that creates the template class and stores it in a pointer of the type of the base class.

class MyInterface {
    virtual void doSomething(...) = 0;
}

template <int T>
class MyTemplateClass : public MyInterface {
    void doSomething(...) { ... };
}

class TemplateAdapter {
    MyInterface* template_class;

    Template(int n) {
        switch(n) {
          case 1:
            template_class = new MyTemplateClass<1>();
            break;
          case 2:
            template_class = new MyTemplateClass<2>();
            break;
          case 3:
            template_class = new MyTemplateClass<3>();
            break;
          [...]
        }
    }

   void doSomething() {
       template_class->doSomething();
   }
}

Now while this does work and yields the correct results, it is very slow. It is almost twice as slow using the adapter than using the template class. It is clear that is has to be somewhat slower, but this is far slower than I'd expected.

Where does this big loss in performance come from? And do you know how to dynamically create a template class with a better performance?

Any help is greatly appreciated! Thanks, Pedro

这种设计不允许编译器内联任何东西(如果在编译时知道实际类型,则可以删除虚拟调用),并且需要对实际实例化的类进行运行时决策。

Template in C++ exists only compile-time, any attempt to dynamically generate template will fail due to this reason.

Your code might be optimized by removing run-time switch and making adapter the template:

template<int i>
class TemplateAdapter {
    MyTemplateClass<i> template_class;

}

but this eliminates any adapter need.

The other answers already explain that templates are a compile time rather than runtime feature. However your question asks why is there such a noticeable performance penalty in your workaround. If you're creating the adapter class frequently, the new keyword is allocating memory from the heap for the child object, and heap allocations are notoriously slow.

Do you need the dependency inversion introduced by MyInterface? If not, why not just create a non-polymorphic and non-templatized type which does the same thing as your Adapter but contains the full implementation of the required functionality...? It would decide what to do based on the integer parameter passed at construction time, without creating new object or calling virtual functions...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM