我有一个模板类
template <class T>
class myClass
{
public:
/* functions */
private:
typename T::Indices myIndices;
};
现在,在我的主代码中,我想根据条件实例化模板类。喜欢 :
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..
}
现在这种方法的问题是auto_ptr<>
将会在年底死去switch{}
。
而且我不能在函数的开头声明它,因为我不知道预先实例化的类型。
我知道我正在尝试在编译时(使用模板)实现运行时的事情,但仍然想知道是否有更好的方法来做到这一点。
创建基类
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..
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)