Cod*_*ain 4 c++ templates smart-pointers
我有一个模板类
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..
}
Run Code Online (Sandbox Code Playgroud)
现在这种方法的问题在于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..
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
862 次 |
| 最近记录: |