繁体   English   中英

专门化类模板的成员函数模板

[英]Specialize member function template of a class template

我有以下代码:

#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=

我认为您不需要专门化它,难道您不可以只为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会有一些查找上的麻烦,但这在这里似乎没有必要。

是的,我认为重载应该可以正常工作,尽管由于参数和模板的匹配顺序可能会发生一些奇怪的事情。

仅出于完整性考虑,以下是使原始示例编译的方法:

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
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM