2009-07-15 75 views
2

我有下面的代碼的成員函數模板:專營類模板

#include <stdio.h> 

template<int A> 
class Thing 
{ // 5 
    public: 
     Thing() : 
      data(A) { 
     } 

     template<int B> 
     Thing &operator=(const Thing<B> &other) { 
      printf("operator=: A = %d; B = %d\n", A, B); 
      printf("this->data = %d\n", data); 
     } 

    private: 
     int data; 
}; 

int main() { 
    Thing<0> a, b; 
    Thing<1> c; 

    a = b; 
    a = c; 
    c = b; 

    return 0; 
} 

我需要專門Thing<A>::operator=A == B。我曾嘗試這樣的:

template<int B> 
template<int A> 
Thing<A> &Thing<A>::template operator=(const Thing<A> &other) { // 23 
    printf("operator= (specialized): A = %d; B = %d; A %c= B\n", A, B, (A == B) ? '=' : '!'); 
    printf("this->data = %d; other.data = %d\n", data, other.data); 
} 

然而,我接收與克++編譯錯誤:

23: error: invalid use of incomplete type ‘class Thing<B>’ 
5: error: declaration of ‘class Thing<B>’ 

我在operator=使用if(A == B)嘗試沒有一個專門化。但是,我收到訪問私人會員data時遇到的錯誤,我需要訪問A == B

如何正確地專門化我的成員函數模板operator=的類模板Thing

回答

2

我不認爲你需要專注它,你就不能提供operator=過載?

template<int A> 
class Thing 
{ // 5 
    public: 
     Thing() : 
      data(A) { 
     } 

     template<int B> 
     Thing &operator=(const Thing<B> &other) { 
      printf("operator=: A = %d; B = %d\n", A, B); 
      printf("this->data = %d\n", data); 
     } 

     Thing &operator=(const Thing &other) { 
      printf("operator overload called"); 
      printf("this->data = %d\n", data); 
     } 

    private: 
     int data; 
}; 

IIRC有一些查找陷阱,如果你嘗試過載與專長相結合,但是,這並不需要看這裏。

+0

我很慚愧我完全忽略了這一點。非常感謝! – strager 2009-07-15 18:13:42

2

是的,我認爲超載應該可以正常工作,但也有一些可能發生由於其參數和模板的匹配順序奇怪的事情。

只是爲了完整性,這裏是如何讓你的原來的例子編譯:

template<int A> 
class Thing 
{ // 5 
... 
template<int B> 
Thing<A> &operator=(const Thing<A> &); 
}; 

template<int A> 
template<int B> 
Thing<A> &Thing<A>::operator=(const Thing<A> &other) { // 23 
    ...