簡體   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