c++ - 在可以转换为另一个模板类型的类模板中重载赋值运算符

标签 c++ templates casting

#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 的值,但仍然是类 的实例编号

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

提前致谢。

最佳答案

你应该这样做:

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,则最好使用 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!
}

关于c++ - 在可以转换为另一个模板类型的类模板中重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8305952/

相关文章:

C++ 动态内存分配 - char*

C++ lpcwstr 到 wstring

c++ - 将 shared_ptr 的集合转换为 weak_ptr 的集合

c++ - 模板特化中的多个 void_t 调用

C++/模板 : Can I selectively disable a function of a class at compile time?

c++ - 具有棘手的 lambda 表达式的奇怪未定义行为

c++ - 结合了 const 和非常量引用数据成员的单一类

delphi - 测试强制转换 OleVariant 是否会引发异常(不引发异常)

c - 我是否要转换 malloc 的结果?

c++ - const int 隐式转换 C++