我有下面的代码的成员函数模板:专营类模板
#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