2009-07-15 82 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 
    ...