我有下面的代碼的成員函數模板:專營類模板
#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
?
我很慚愧我完全忽略了這一點。非常感謝! – strager 2009-07-15 18:13:42