Re: [問題] template一問
看板C_and_CPP (C/C++)作者developers (alpine skier)時間15年前 (2011/06/18 13:09)推噓1(1推 0噓 4→)留言5則, 3人參與討論串2/9 (看更多)
: Base* Get( int iType )
: {
: switch( iType )
: {
: case 1:
: return new D1;
: break;
: case 2:
: return new D2;
: break;
: case 3:
: return new D3;
: break;
: }
: }
: 像這種東西在以後type增減的狀況下必須不斷對Get()做調整
: 請問有沒有什麼方法可以解決這種問題?
可以使用full template specialization
每增加一種新的type就要多宣告一個新的specialization
好處是不用回頭修改原本的function
template<class T>
Base* Get()
{
return new T;
}
template<>
Base* Get<D1>()
{
return new D1;
}
template<>
Base* Get<D2>()
{
return new D2;
}
template<>
Base* Get<D3>()
{
return new D3;
}
int main()
{
Base* pD1 = Get<D1>();
Base* pD2 = Get<D2>();
Base* pD3 = Get<D3>();
delete pD1;
delete pD2;
delete pD3;
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 98.254.62.107
→
06/18 13:35, , 1F
06/18 13:35, 1F
推
06/18 17:14, , 2F
06/18 17:14, 2F
→
06/18 17:15, , 3F
06/18 17:15, 3F
→
06/18 17:16, , 4F
06/18 17:16, 4F
→
06/18 23:43, , 5F
06/18 23:43, 5F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章