Domanda

I have the following code:

#include <iostream>
using namespace std;

template<typename T> class myclass {
public:
    T data;

    myclass(T const & _data = T()) : data(_data) {}

    template<typename U> myclass<T> & operator=(myclass<U> const & rhs) {
        cout << data << " = " << rhs.data << endl;
        return *this;
    }
};

int main() {
    myclass<double> first(1);
    myclass<float> second(2);
    myclass<double> third(3);
    first=second;
    first=third;
}

Now, althought it compiles perfectly, the output is only:

1 + 2

Why isn't first=third making a call to

myclass<double> & operator=(myclass<double> const & rhs)

?

È stato utile?

Soluzione

The copy assignment operator is never a function template. Since the class doesn't declare a copy assignment operator the compiler generates one and uses this generated operator. If you add an operator like this, you'll see the assignment:

myclass<T>& operator= (myclass<T> const& rhs) {
    std::cout << "(copy) " << data << " = " << rhs.data << '\n';
    return *this;
}

Altri suggerimenti

The copy-assignment operator is never a template. Since you didn't define one, a default-version is defined for you (which doesn't print anything).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top