小编Sar*_*ara的帖子

C++模板问题添加两种数据类型

我有一个带有重载+运算符的模板类.当我添加两个或两个双打时,这工作正常.如何将它添加到int和double并返回double?

template <class T>
class TemplateTest
{
private:
  T x;

public:

  TemplateTest<T> operator+(const TemplateTest<T>& t1)const
  {
    return TemplateTest<T>(x + t1.x);
  }
}

in my main function i have

void main()
{
  TemplateTest intTt1 = TemplateTest<int>(2);
  TemplateTest intTt2 = TemplateTest<int>(4);
  TemplateTest doubleTt1 = TemplateTest<double>(2.1d);
  TemplateTest doubleTt2 = TemplateTest<double>(2.5d);

  std::cout <<  intTt1 + intTt2 << /n;
  std::cout <<  doubleTt1 + doubleTt2 << /n;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够做到这一点

std::cout <<  doubleTt1 + intTt2 << /n;
Run Code Online (Sandbox Code Playgroud)

c++ templates

14
推荐指数
3
解决办法
7275
查看次数

标签 统计

c++ ×1

templates ×1