Overloading an assignment operator in a class template that may use a different type of template

#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 

Overloading the comment handler with comments is my attempt to do what I want, I thought it might give a better description than the description above the fragment.

I want to be able to do the following:

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

Where a will then be sent to int and set to b , but will still be an instance of the Number class.

Is it possible? Can you help me here?

Thanks in advance.

+4
source share
2 answers

You must 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 the return type!

I would prefer to use a different letter for the 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 casting if you want to use the class type as an argument to a template and whose constructor has been declared explicit :

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

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

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

You have some of T 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 allow you to do

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

and it will print 6 , a behavior similar to the type of int and float types that you simulate.

+4
source

Source: https://habr.com/ru/post/1383559/


All Articles