多參數樣板函式:可以宣告多個樣板參數型別,讓一個樣板函式可以輸入多個樣板參數,如:
class jewelry // 建立一類別jewelry
{
public:
int price;
string kind;
jewelry(string kind_,int price_){kind=kind_;price=price_;}
};
class car //建立一類別car
{
public:
int price;
string kind;
car(string kind_,int price_){kind=kind_;price=price_;}
};
class art //建立一類別art
{
public:
int price;
string kind;
art(string kind_,int price_){kind=kind_;price=price_;}
};
template <class X, class Y> //宣告樣板參數型別X,Y
void which_is_more_valuable(X x,Y y) //宣告樣板函式which_valuable
{
if(x.price>y.price){cout<<x.kind<<" is valuable than "<<y.kind<<endl;}
else if(x.price<y.price){cout<<y.kind<<" is valuable than "<<x.kind<<endl;}
else {cout<<"same";}
}
int main() //主程式在此
{
jewelry j1("ruby",500);
car c1("ford",600);
art a1("paint",700);
which_is_more_valuable (j1,c1); //顯示:ford is valuable than ruby
which_is_more_valuable (a1,c1); //顯示:paint is valuable than ford
}
由以上可知,樣板函式which_is_more_valuable可以輸入兩個樣板參數,而且不限所輸入的參數型別,此乃樣板函式之功效所在。
留言列表