Re: [問題] template一問
: 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
討論串 (同標題文章)