【问题标题】:Specialize member function template of a class template特化类模板的成员函数模板
【发布时间】: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&lt;A&gt;::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=

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    我认为你不需要专门化它,你不能只为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 会有一些查找陷阱,但在这里看起来没有必要。

    【讨论】:

      【解决方案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
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 2013-12-20
        • 1970-01-01
        • 2021-09-11
        • 2022-01-10
        相关资源
        最近更新 更多