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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With