在可强制转换为另一个模板类型的类模板中重载赋值操作符

Overloading assignment operator in a class template that can cast to another template type

本文关键字:重载 赋值操作符 类型 转换 另一个      更新时间:2023-10-16
#ifndef NUMBER_HPP
#define NUMBER_HPP
template <class T>
class Number
{
public:
  Number( T value ) : m_value( value )
  {
  }
  T value() const
  {
    return m_value;
  }
  void setValue( T value )
  {
    m_value = value;
  }
  Number<T>& operator=( T value )
  {
    m_value = value;
  }
  //  template <class T2>
  //  Number<T2>& operator=( const Number<T>& number )
  //  {
  //    m_value = number.value();
  //    return *this;
  //  }
private:
  T m_value;
};
typedef Number<int> Integer;
typedef Number<float> Float;
typedef Number<double> Double;
#endif // NUMBER_HPP

注释的赋值操作符重载是我想做的事情,我认为它可能比上面的代码片段提供更好的描述。

我希望能够做到以下几点:

Float a(10);
Integer b(20);
a = b;

其中a将被强制转换为int并给定b的值,但仍然是Number类的实例。

有可能吗?你能帮我一下吗?

你应该这样做:

template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
    m_value = number.value();
    return *this;
}

也就是说,在参数类型中使用T2,而不是在返回类型中!

我宁愿使用不同的字母作为模板参数:

template <class U>
Number<T>& operator=( const Number<U>& number )
{
    m_value = number.m_value; //I would also directly access the member variable!
    return *this;
}

我认为,最好使用显式强制转换,如果你想使用类类型作为模板参数,其构造函数已声明为explicit:

 m_value = static_cast<T>(number.m_value); 

顺便说一下,其他operator=应该实现为:

Number<T>& operator=(T const & value ) //accept by const reference
{
    m_value = value;
    return *this; //you've to return!
}

您有一些T s在错误的地方。应该是

template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
    m_value = number.value();
    return *this;
}

这将允许您执行

Integer a(4);
Float b(6.2f);
a = b;
cout << a.value() << endl;

,它将打印6,行为类似于您正在模仿的intfloat类型。