Lorenzo Pistone
Lorenzo Pistone

Reputation: 5188

why template operator overloading doesn't work?

Why doesn't this code print "operator="?

#include <iostream>
using namespace std;

class A{
public:
    template<typename T> void operator=(const T& other){
        cout<<"operator="<<endl;
    }
};

int main(){
    A a;
    A b;
    a=b;
}

Upvotes: 1

Views: 511

Answers (1)

Xeo
Xeo

Reputation: 131907

The compiler generated copy assignment operator is chosen by overload resolution:

class A{
public:
  A& operator=(A const& other){
    std::cout << "copy assignment\n";
    return *this;
  }
  template<class T>
  void operator=(T const& other){
    std::cout << "templated assignment\n";
  }
};

Will print "copy assignment" and is essentially equal to what the compiler will generate for you (without the printing, of course).

Upvotes: 7

Related Questions