【发布时间】:2009-07-16 02:22:22
【问题描述】:
我有以下代码:
#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);
}
但是,我收到 g++ 编译错误:
23: error: invalid use of incomplete type ‘class Thing<B>’
5: error: declaration of ‘class Thing<B>’
我曾尝试在 operator= 中使用 if(A == B) 而不进行专业化。但是,我在访问私有成员 data 时收到错误消息,我需要访问 A == B 的位置。
我怎样才能正确地特化类模板Thing的成员函数模板operator=?
【问题讨论】: