简体   繁体   中英

Default assignment operator for template class with different template parameters

When compiling the following:

template <class T>
class Number
{
    private:
        T num;
    public:
        Number() {}
        Number( T n ) : num(n) {}
        operator T() const { return num; }
};

int main()
{
    Number<int> n=5;
    Number<char> c=4;
    int i;

    c=int(5);
    i=n;
    c=n;

    return 0;
}

The compiler gets stuck at the third assignment saying there is no match for operator= in c=n . Shouldn't n get converted to int , which in turn will be assigned to c ?

According to the standard, at most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value. Here, you are expecting the compiler to apply the constructor for Number<char> and the conversion operator for Number<int> . See: https://stackoverflow.com/a/867804/677131 .

That's because there is no int operator when your templated class is constructed with the templated type as char .

You actually don't have an assigment operator here, only a constructor and a type operator. This means your compiler would likely have put in a default one probably along the lines of:

Number<T>& operator=( Number<T>& rhs );

You should implement your own assignment operator, this should fix your problem. A generic solution could be as follows, but relies on a valid assignment between the types.

template <typename T, typename V>
class Number
{
    private:
        T num;
    public:
        Number() {}
        Number( T n ) : num(n) {}
        operator T() const { return num; }
        operator=( V& rhs ){ num = rhs; // etc }
};

You also need to make your class constructor explicit to avoid implicit conversion (unless that is what you want).

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