0

例如,我有以下一段代码。

template <class T>
void g(T b){
  ;
}

template <class T>
void h(T b){
   ;
}

class T{
   method X;
   method Y;
   method Z; //many methods but the implementation of the methods are different from TT
};

class TT{
   method X;
   method Y;
   method Z; //the implementation of the methods are different from T
}
void f(){

  if(a==1){
  T b;  //use type T to define b
  } else{
  TT b; //use type TT to define b
  }

 g(b);
 h(b);
 i(b);// I need to use b for many different functions.

}

我还需要变量 b 的范围在函数 f 中。

在类 T 和 TT 中,有许多方法,但方法的实现是不同的。

有什么建议么?

4

1 回答 1

1

使用模板并移动您在f()其中将使用的代码binside DoStuff()

template <class Type>
void DoStuff()
{
  Type b;  //use type 'Type' to define b      
}

void f(){

  if(a==1){
    DoStuff<T>();
  } else{
    DoStuff<TT>();
  }

}
于 2013-03-19T15:34:05.170 回答