在运行时有条件地实例化模板 [英] Conditionally instantiate a template at run-time

查看:27
本文介绍了在运行时有条件地实例化模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板类

<预><代码>模板类我的类{民众:/* 职能 */私人的:typename T::Indices myIndi​​ces;};

现在在我的主代码中,我想根据条件实例化模板类.喜欢:

<预><代码>myFunc(int 操作){开关(操作){案例0://使用 <A> 实例化 myClassauto_ptr >ptr = new myClass();情况1://使用 <B> 实例化 myClassauto_ptr ();案例2://使用 <C> 实例化 myClass....}//这里使用ptr..}

现在这种方法的问题是 auto_ptr<> 将在 switch{} 结束时消失.而且我不能在函数的开头声明它,因为我不知道事先会实例化的类型.

我知道我正在尝试在编译时(使用模板)实现运行时的事情,但仍然想知道是否有更好的方法来做到这一点.

解决方案

创建基类

class Base {受保护:虚拟 ~Base() {}//... 职能};模板类 myClass : 基础 {//...};myFunc(int 操作){shared_ptr <基地 >指针;开关(操作){案例0://使用 <A> 实例化 myClassptr.reset ( new myClass () );情况1://使用 <B> 实例化 myClassptr.reset ( new myClass () ) ;案例2://使用 <C> 实例化 myClass....}//这里使用ptr..}

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..
}

这篇关于在运行时有条件地实例化模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆