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

前端 未结 2 2055
一向
一向 2020-12-16 05:18
#ifndef NUMBER_HPP
#define NUMBER_HPP

template 
class Number
{
public:
  Number( T value ) : m_value( value )
  {
  }

  T value() const
  {
    retu         


        
相关标签:
2条回答
  • 2020-12-16 05:27

    You should do this:

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

    That is, use T2 in the parameter type, not in the return type!

    I would rather use different letter for template parameter:

    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;
    }
    

    I think, it is better to use explicit cast, if you want to use class type as template argument and whose constructor has been declared explicit:

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

    By the way, the other operator= should be implemented as:

    Number<T>& operator=(T const & value ) //accept by const reference
    {
        m_value = value;
        return *this; //you've to return!
    }
    
    0 讨论(0)
  • 2020-12-16 05:42

    You have some of the Ts in the wrong place. It should be

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

    This will let you do

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

    and it will print 6, a behaviour similar to that of the int and float types you are imitating.

    0 讨论(0)
提交回复
热议问题