[英]Class template interaction
實際上,我相當確定可以在以前創建的線程之一中找到我的問題的答案。 特別是, 為什么必須在何處以及為什么要放置“模板”和“類型名”關鍵字? 這對模板/類型名的歧義化有很好的解釋。 但是,我很茫然,因為我實際上無法將概念擴展到我的代碼(即相互交互的類模板)中。
在此線程中,我認為我看到的錯誤與代碼中的錯誤相同。 為什么要回答使用A<B>
其中B是類)而不是A<T>
其中T是我們實際上想要的類型名稱模板)來定義typedef的答案。
但是,我嘗試了這些選項都沒有用。 這是代碼。 謝謝您的幫助。
#include "testTemplateA.h"
template<typename A>
class testTemplateB {
public:
// none of these work
typedef testTemplateA<A> templateType;
typedef typename testTemplateA<A> templateType;
typedef typename testTemplateA<testTemplateB> templateType;
testTemplateB(templateType& TA) {}
~testTemplateB(void) {}
};
#include "testTemplateB.h"
template<typename A>
class testTemplateA
{
public:
testTemplateA(void) {}
~testTemplateA(void) {}
void callUponB(void) {
testTemplateB<A> g = testTemplateB<A>(this);
}
};
問題在這里
typedef testTemplateA<A> templateType;
您正在使用Class Template創建一個模板類
template<typename A>
class testTemplateA
在創建模板類時,您需要提供實際的類型。 所以應該是這樣
typedef testTemplateA<< testTemplateB<int >> templateType;
如果希望T總是一個類,建議使用“ class ”,如果可以預期使用其他類型(int,char *,float等等),則建議使用“ typename ”。 考慮它為用法提示。
與模板語法問題相比,這看起來更像是循環依賴問題。 只要您可以定義一個不完整的類,就可以執行以下操作:
// Begin testTemplateA.h
#ifndef TEST_TEMPLATE_A_H
#define TEST_TEMPLATE_A_H
template<typename A>
class testTemplateA
{
public:
testTemplateA(void) {}
~testTemplateA(void) {}
void callUponB(void); // Can't be defined here!
};
#include "testTemplateB.h"
template<typename A>
void testTemplateA<A>::callUponB(void) {
testTemplateB<A> g = testTemplateB<A>(this);
}
#endif
// End testTemplateA.h
// Begin testTemplateB.h
// Yes, the include is outside the define guard.
#include "testTemplateA.h"
#ifndef TEST_TEMPLATE_B_H
#define TEST_TEMPLATE_B_H
template<typename A>
class testTemplateB {
public:
typedef testTemplateA<A> templateType;
testTemplateB(templateType& TA) {}
~testTemplateB(void) {}
};
#endif
// End testTemplateB.h
如果源文件僅包含testTemplateA.h,它將看到testTemplateA的類模板定義,然后包含testTemplateA
的全部內容,然后查看testTemplateA.h中依賴於testTemplateB
的成員定義。 如果源文件僅包含testTemplateB.h,它將立即以testTemplateA.h開頭,該文件仍將在中間包含testTemplateB.h並獲得相同的結果。 如果源文件中的任何一個按順序包含兩者,則第二個文件將無效,因為兩者都已包含在內。
您只需要在至少包含一個::
標記的名稱前使用typename
關鍵字。
另一件事:您的構造函數testTemplateB(templateType& TA);
需要引用,但是您的語句testTemplateB<A> g = testTemplateB<A>(this);
傳遞指針值this
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.