C++中通用模板的使用

 1 #include<iostream>
 2 using namespace std;
 3 // 通用模板计算一个表达式的值
 4 template<class Ta,class Tb,class Tc>
 5 Ta Abc(const Ta *a,const Tb *b,const Tc *c)
 6 {
 7     return (*a)+(*b)+(*c);
 8 }
 9 int main()
10 {
11     int a=10,*p;
12     float b=2.6,*q;
13     char c='A',*r;
14     p=&a;
15     q=&b;
16     r=&c;
17     cout<<"*p= "<<*p<<",*q= "<<*q<<",*r="<<int(*r)<<endl;
18     cout<<Abc(p,q,r)<<endl;
19     return 0;
20 }
 程序中通过template<class Ta,class Tb,class Tc>使得a,b,c3个参数可以为不同类型;且返回结果类型为第一个参数的类型;
调试运行结果为:












原文地址:https://www.cnblogs.com/yuzhuwei/p/4172350.html