Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally instantiate a template at run-time

I have a template class


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

Now in my main code I want to instantiate the template class depending on a condition. Like :


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

Now the problem with this approach is that the auto_ptr<> will die at the end of switch{}. And I can't declare it at the beginning of the function, because I don't know the type that will be instantiated before-hand.

I know I'm trying to achieve a run-time thing at compile-time (using template), but still wanted to know if there is some better way to do this.

like image 711
CodeRain Avatar asked Dec 09 '22 18:12

CodeRain


2 Answers

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..
}
like image 141
Alexey Malistov Avatar answered Dec 17 '22 09:12

Alexey Malistov


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.

like image 45
sharptooth Avatar answered Dec 17 '22 11:12

sharptooth