多个数据类型的单个模板对象

时间:2013-11-14 17:46:45

标签: c++ templates

class mypair {
    T a, b;
  public:
    mypair (T first, T second)
      {a=first; b=second;}
    T getmax ();
};

template <class T>
T mypair<T>::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  int i;
  cin>>i;
  if(i==0)
      mypair <int> myobject (100, 75);
  else
      mypair <float> myobject (100, 75);

  cout << myobject.getmax();
  return 0;
}

我想根据i的值创建模板类的单个对象。如果i的值为0,则创建数据类型int else float的模板类。 上面的程序抛出一个错误'myobject'没有在我调用getmax函数的第二行最后一行中声明。

我如何实现&gt;

3 个答案:

答案 0 :(得分:2)

为什么不写一个功能模板来做这项工作?

template <typename T>
doStuff()
{
  mypair <T> myobject (100, 75);
  std::cout << myobject.getmax();
}

然后

if(i==0)
  doStuff<int>();
else
  doStuff<float>();

答案 1 :(得分:0)

问题在于范围:

if(i==0)
{
      mypair <int> myobject (100, 75);
} // myobject is now out of scope and unusable
  else
{
      mypair <float> myobject (100, 75);
}  // myobject is now out of scope and unusable

您需要为模板声明一个nontemplate基础 然后你可以声明一个指向基数的指针 在你的if子句中做一个新的 然后你可以使用下面代码中的指针

顺便说一句,即使对于单行块

,它总是有用{}

答案 2 :(得分:0)

这是因为if和else案例的范围...... 你可以通过这样做来实现这个目标

if(i==0){
  mypair <int> myobject (100, 75);
  cout << myobject.getmax();
} 
else{
  mypair <float> myobject (100, 75);
  cout << myobject.getmax();
}

由于对象在if和else范围内是活着的,因此它将会死亡。

if{
     // alive scope
 }
 //dead scope