Conditionally instantiate a template at run-time
c++, smart-pointers, templates
Solution
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..
}
Problem
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.