简体   繁体   中英

Could I overload operator= to assign object of a class to a variable of another class but both class are from the same class template

For example, I have a class

template<class T>
class Number
{
private:
    T number;
public:
    Number(T num)
    {
        number=num;
    }
    void operator=(T num)
    {
        number=num;
    }
}

how can I overload the assign operator to assign a Number<char> object to a variable of type Number<int>, or specialize a method of one type with the parametres of another type of the same template? By the way, is it possible to make an alias of class template, Number<char>, as "MyChar" so I don't need to use the class name Number<char> anymore but the alias MyChar

Make assignment operator a template member function with a separate type parameter:

// Make sure the template on U can access private number
template <class U> friend class Number;

template<class U>
Number<T>& operator=(const Number<U>& num)
{
    number = static_cast<T>(num.number);
    return *this;
}

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM