Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C++;?_C++ - Fatal编程技术网

C++ 如何在C++;?

C++ 如何在C++;?,c++,C++,例如,我有下面的一段代码 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

例如,我有下面的一段代码

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.
模板
无效g(T b){
;
}
模板
空位h(tb){
;
}
T类{
方法X;
方法Y;
方法Z;//方法很多,但方法的实现与TT不同
};
TT类{
方法X;
方法Y;
方法Z;//这些方法的实现不同于T
}
void f(){
如果(a==1){
tb;//使用类型T定义b
}否则{
TT b;//使用TT类型定义b
}
g(b);
h(b);
i(b);//我需要对许多不同的函数使用b。
}

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

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

有什么建议吗?

使用并移动
f()
中的代码,该代码将在
DoStuff()中使用
b

模板
void DoStuff()
{
类型b;//使用类型“Type”定义b
}
void f(){
如果(a==1){
DoStuff();
}否则{
DoStuff();
}
}

与此完全相同,如果您仅在这些
{}
中使用
b
,则这很好。否则,你就不能(轻松地或干净地)去做。有各种各样的麻烦的方法来满足你的要求,但通常的解决方法是做一些完全不同的事情。问一下您想从中得到什么,我们可以提出更好的解决方案。请说明您打算如何使用
b
如果TT和T是不相关的类型,您希望如何使用
if
之后的对象?e、 g.当方法可以有完全不相关的接口时,您打算如何在其上调用方法?谢谢。但是变量b的范围呢?我需要将其用于函数f。@user2145796移动您在函数
f
中的代码,该函数使用
b
内部
DoStuff
。Zadirion谢谢。我在f里面还有很多其他的事情要做。还有其他建议吗?如果这些东西在
f
中工作,那么它们为什么不能在
DoStuff
中工作呢?@ZdeslavVojkovic如果我将所有函数f、g和h移到DoStuff,这几乎与使用f作为模板一样。我只是经常使用b,但我不希望f成为T类和TT类的模板。我在考虑是否有一种使用“typedef”的方法,例如,如果(a==1)typedef T cos;否则,你就没有罪;tb;
template <class Type>
void DoStuff()
{
  Type b;  //use type 'Type' to define b      
}

void f(){

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

}