[問題] template一問
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
問題(Question):
請問各位
現在小弟遇到一個問題
請看以下
class Base
{
public: virtual void Run() = 0;
};
class D1 : public Base
{
public: void Run() { std::cout << "Run D1"; }
};
class D2 : public Base
{
public: void Run() { std::cout << "Run D2"; }
};
class D3 : public Base
{
public: void Run() { std::cout << "Run D3"; }
};
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()做調整
請問有沒有什麼方法可以解決這種問題?
小弟有想到要用template的方式做
template< class T >
class DerivedCreator
{
public:
Base* Get()
{
return &m_DerivedObj;
}
T m_DerivedObj;
};
但原本的Base* Get(int iType)又該怎麼寫呢?
Base* Get( int iType )
{
// ????????????????????????
}
template的type有辦法在runtime中當做參數傳進去嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.124.99.126
→
06/17 16:41, , 1F
06/17 16:41, 1F
→
06/17 17:22, , 2F
06/17 17:22, 2F
→
06/17 17:29, , 3F
06/17 17:29, 3F
→
06/17 17:30, , 4F
06/17 17:30, 4F
→
06/17 17:35, , 5F
06/17 17:35, 5F
→
06/17 17:36, , 6F
06/17 17:36, 6F
→
06/17 17:36, , 7F
06/17 17:36, 7F
→
06/17 17:36, , 8F
06/17 17:36, 8F
→
06/17 17:37, , 9F
06/17 17:37, 9F
→
06/17 17:37, , 10F
06/17 17:37, 10F
→
06/17 17:37, , 11F
06/17 17:37, 11F
→
06/17 17:39, , 12F
06/17 17:39, 12F
→
06/17 17:40, , 13F
06/17 17:40, 13F
→
06/17 17:42, , 14F
06/17 17:42, 14F
※ 編輯: NIKE74731 來自: 59.124.99.126 (06/17 18:07)
→
06/17 18:11, , 15F
06/17 18:11, 15F
→
06/18 13:45, , 16F
06/18 13:45, 16F
→
06/18 13:45, , 17F
06/18 13:45, 17F
→
06/18 15:02, , 18F
06/18 15:02, 18F
討論串 (同標題文章)