#include <iostream>
#include <vector>
using namespace std;
/*用多態來實現的話需要
<1>定義時注意:
1.定義
class Base
{
virtual ShowDemo() const = 0;
};
2.剝離抽象業務放到公用類中
3.讓 Derived1, Derived2都從Base 繼承而來
4.子類必須實現介面函數
<2>使用時注意
1.處理業務函數的參數只能使用 Base& 或者 Base* 方式傳遞對象地址,
讓其在運行期判別類型找到對應函數
2.每次繼承增加一張虛表增加資源開銷。
*/
class Derived1
{
public:
void ShowDemo() const { cout<<"Derived1::ShowDemo()"<<endl; }
};
class Derived2
{
public:
void ShowDemo() const { cout<<"Derived2::ShowDemo()"<<endl; }
};
//使用模板演繹實參,直接在運行期就得到確定的物件類型
//只不過使用泛型,少了對ShowDemo做重載,但其實執行個體化了兩次
//因為僅僅針對於這一整類使用泛型可以,但是如果傳入的T為其他類型呢
//靜態檢測會發現問題,發現結構無此函數
template< typename T >
void ShowDemo( T const& t_g )
{
t_g.ShowDemo();
}
template< typename T1, typename T2 >
void EffecEach( T1 const& t_g_1, T2 const& t_g_2 )
{
t_g_1.ShowDemo();
t_g_2.ShowDemo();
}
template < typename T >
void ShowDemoAll( vector<T> const& t_v_g )
{
for( int i = 0; i < t_v_g.size(); i++ )
t_v_g[i].ShowDemo(); //
}
void main()
{
Derived1 t_d_1;
Derived2 t_d_2;
ShowDemo(t_d_2);
ShowDemo(t_d_1);
EffecEach( t_d_1, t_d_2 );
vector<Derived2> coll;
coll.push_back(t_d_2);
ShowDemoAll(coll);
}