簡體   English   中英

模板 class 與模板 function

[英]Template class with template function

誰能告訴這段代碼有什么問題?

template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X, class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

匯編:

$ g++ source.cpp 
source.cpp:8: error: prototype for ‘void C<X>::f(Y)’ does not match any in class ‘C<X>’
source.cpp:4: error: candidate is: template<class X> template<class Y> void C::f(Y)

我現在可以通過在第 4 行聲明和定義 function 來完成任務,但是與單獨執行相比,同時聲明和定義 function 會產生什么后果? (這不是關於在 header 與源文件中聲明 function 的討論)

注意:我見過這個問題,但似乎唯一讓我感興趣的部分被分開了=(

編譯器已經告訴你答案了。 The class C is a template with one parameter, and the member function f is a template member function, and you have to define it in the same way:

template <class X>
template <class Y>
void C<X>::f(Y y)
{
    // Something.
}

如果您在聲明站點定義 function,您將隱式聲明它inline 這實際上是唯一的區別。 當然,可能存在風格上的考慮,例如永遠不要將 function 定義放在 class 定義中。

正如您正確觀察到的,您仍然必須在 header 文件中提供定義,因為您需要在使用模板時實例化它,因此您需要訪問所有定義。

該錯誤准確地告訴您,您的代碼應如下所示:

template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X> template<class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

您的 class 未定義為template<class X, class Y>

順便說一句,最好在模板參數列表中使用關鍵字“typename”而不是“class”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM