2012-01-25 113 views
1

爲什麼此代碼不打印「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; 
} 
+5

因爲它只是一個賦值運算符,所以不會阻止編譯器隱式生成_copy-assignment_運算符,這是實際在此調用的。 – ildjarn

回答

7

編譯器生成的拷貝賦值運算符是重載選擇:

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"; 
    } 
}; 

將打印「拷貝賦值」和基本上等於什麼編譯器會爲您(不印刷,課程)。

+0

我知道運算符=正在被編譯器合成。隱含的問題是:有沒有辦法強制它使用我的operator = template? –

+0

您可以將其他人定義爲私人和空的,以便不使用它們。 – AJG85

+0

@ildjarn:沒有,重載解析仍然會選擇私人的並觸發訪問/刪除錯誤。訪問檢查不是在重載解析期間完成的,而是之後才進行的。 – Xeo