添加两种数据类型的C ++模板问题 [英] C++ Template problem adding two data types

查看:108
本文介绍了添加两种数据类型的C ++模板问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有重载+运算符的模板类。这是工作正常,当我添加两个int或两个双打。

I have a template class with an overloaded + operator. This is working fine when I am adding two ints or two doubles. How do I get it to add and int and a double and return the 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;
}

我也想这样做

std::cout <<  doubleTt1 + intTt2 << /n;


推荐答案

你会进入c ++的部分,这可能会导致很多问题发布到StackOverflow :)想想很长很难,如果你真的想这样做。

Here be dragons. You're getting into parts of c++ that will probably result in a lot of questions posted to StackOverflow :) Think long and hard about if you really want to do this.

从容易的部分开始,你想允许 operator + 添加不总是与 T 相同的类型。开始:

Start with the easy part, you want to allow operator+ to add types that are not always the same as T. Start with this:

template <typename T2>
TemplateTest<T> operator+(const TemplateTest<T2>& rhs) {
  return TemplateTest<T>(this->x + rhs.x);
}

注意,这是 T2 以及 T 。添加 doubleTt1 + intTt2 时, T 将为 doubleTt1 T2 将会是 intTt2

Note that this is templated on T2 as well as T. When adding doubleTt1 + intTt2, T will be doubleTt1 and T2 will be intTt2.

这是整个方法的大问题。

But here's the big problem with this whole approach.

现在,当你添加一个 double int ,你期望什么? 4 + 2.3 = 6.3 ?或 4 + 2.3 = 6 ?谁会期望 6 ?你的用户应该,因为你将双引号转换为 int ,从而失去小数部分。有时。取决于哪个操作数是第一个。如果用户写 2.3 + 4 ,他们会得到(如预期的) 6.3 。令人困惑的图书馆让悲伤的用户。如何最好地处理呢? I dunno ...

Now, when you add a double and an int, what do you expect? 4 + 2.3 = 6.3? or 4 + 2.3 = 6? Who would expect 6? Your users should, because you're casting the double back to an int, thus losing the fractional part. Sometimes. Depending on which operand is first. If the user wrote 2.3 + 4, they would get (as expected?) 6.3. Confusing libraries make for sad users. How best to deal with that? I dunno...

这篇关于添加两种数据类型的C ++模板问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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