Conditionally instantiate a template at run-time

北城余情 提交于 2019-11-29 14:45:30

Create a base class

class Base {     
  protected:
      virtual ~Base() {}
      //... functions
};

template <class T> class myClass : Base { 
  //...
};

myFunc( int operation){ 
   shared_ptr < Base >  ptr;

   switch (operation) {        
     case 0:            
          // Instantiate myClass with <A>             
          ptr.reset ( new myClass<A> () );        
     case 1:            
          // Instantiate myClass with <B>             
          ptr.reset ( new myClass<B> () ) ;        
      case 2:            
           // Instantiate myClass with <C>         ....    
     }    
     // Use ptr here..
}

You could introduce a common base to myClass and use that as the parameter to auto_ptr. Just don't forget to declare that common base's destructor virtual.

Boost.Variant should do the trick.

myFunc( int operation)
{
    boost::variant< myclass<A>, myclass<B> > obj;
    switch (operation) {
        case 0:
            // Instantiate myClass with <A> 
            obj = myClass<A> ();
        case 1:
            // Instantiate myClass with <B> 
            obj = myClass<B> ();
        case 2:
            // Instantiate myClass with <C> 
        ....
    }
    // Use object here..
}

Using the object is a little different because the type is dynamically determined. The apply_visitor technique is definitely the way to go; see the tutorial for how to use it.

You can add a level of indirection to get what you want. You can avoid a base class with virtual methods and doing any other special stuff.

For example:

template <class T> 
class MyClass
{
    public:
        /* functions */
    private:
        typename T::Indices myIndices;  
};

template<typename T>
static void doit()
{
    MyClass<T> t;
    // Use t here.
}

void myfunc(int op)
{
    switch (op) {
        case 0: return doit<A>();
        case 1: return doit<B>();
        // ...
     }
 }

low tech solution. use a regular pointer with the scope you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!