Re: [問題] template一問

看板C_and_CPP作者 (綠豆嘉義人)時間13年前 (2011/11/10 15:34), 編輯推噓2(201)
留言3則, 2人參與, 最新討論串9/9 (看更多)
這個應該很正常吧 沒 instantiation之前 你要在裡面寫什麼 compiler也不會管你 Ex. 下面是可以編譯過的. 把Foo<A>(a) demark就錯了 template <typename T> void Foo(const T& x) { x.AnyFunction(); } class A {}; void main ( void ) { A a ; //Foo<A>(a); } ※ 引述《gogohata (沒有不可能)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : Visual C++ 2008 : 問題(Question): : TEnMap與STL的Map操作類似 : 請問一下第二個class CItemInfoPool::AddItemInfo 裡面為何 : 可以直接這樣寫 pNewItemInfo->SetItemCode(strItemCode); : 她是怎麼解析到T為CItemInfoBase? : 另外我如果把<typename T> 代成其他類型,像int,這樣是不是就error了? : //Source Code : class CItemInfoBase : { : public: : typedef TEnMap<CEnAString, CItemInfoBase*> ItemInfoMAP; : typedef ItemInfoMAP::iterator ItemInfoMAP_ITER; : typedef ItemInfoMAP::const_iterator ItemInfoMAP_CITER; : typedef ItemInfoMAP::reverse_iterator ItemInfoMAP_RITER; : typedef ItemInfoMAP::const_reverse_iterator ItemInfoMAP_CRITER; : typedef ItemInfoMAP::value_type ItemInfoMAP_VTYPE; : /* 中略 */ : public: : CItemInfoBase& operator = (const CItemInfoBase& info) : { : m_strItemCode = info.m_strItemCode; : return *this; : } : public: : void SetItemCode(const CEnAString& strItemCode){m_strItemCode=strItemCode;} : const CEnAString& GetItemCode() const {return m_strItemCode;} : protected: : CEnAString m_strItemCode; : }; : //------------------------------------------------------------------------- : class CItemInfoPool : { : public: : /* 中略 */ : template <typename T> : T* AddItemInfo(const CEnAString& strItemCode, const T& ItemInfo) : { : CItemInfoBase::ItemInfoMAP_ITER found=m_mapItemInfos.find(strItemCode); : if (found != m_mapItemInfos.end()) : return (T*)found->second; : T* pNewItemInfo = new T; : *pNewItemInfo = ItemInfo; : pNewItemInfo->SetItemCode(strItemCode); : m_mapItemInfos[strItemCode] = pNewItemInfo; : m_iNumOfItemInfos++; : return pNewItemInfo; : } : const CItemInfoBase::ItemInfoMAP& GetItemInfos() const{return m_mapItemInfos;} : protected: : CItemInfoBase::ItemInfoMAP m_mapItemInfos; : }; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 119.77.165.173

11/11 11:23, , 1F
這邊有個疑問,如果AnyFunction是個pure virtual function
11/11 11:23, 1F

11/11 11:24, , 2F
這樣還可以編譯過嗎
11/11 11:24, 2F

11/11 11:47, , 3F
可以 (提示:x 是 const reference to T)
11/11 11:47, 3F
文章代碼(AID): #1Ek-y7Wd (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
問題
5
34
完整討論串 (本文為第 9 之 9 篇):
問題
2
3
問題
5
34
問題
3
16
問題
3
7
問題
1
4
問題
1
2
問題
1
5
問題
0
18
文章代碼(AID): #1Ek-y7Wd (C_and_CPP)