为什么模板运算符重载不起作用?

why template operator overloading doesn't work?

本文关键字:不起作用 重载 运算符 为什么      更新时间:2023-10-16

为什么这个代码不打印"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;
}

编译器生成的副本分配运算符由重载解析选择:

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

将打印"副本分配",基本上等于编译器为您生成的内容(当然,没有打印)。