#include <iostream>
#include<vector>
#include<list>
using namespace std;
using std::function;
template<class T>
void showall(vector<T> v)//数据类型未知
{
for (auto i:v)
{
cout << i << " ";
}
cout << endl;
}
//函数模板嵌套 不管传递过来什么类型 都可以挨个输出
void main()
{
vector<int>myint{ 2, 4, 6, 8, 0 };//vector也是个模板
vector<char>mychar{'a','b','c','d'};
for (auto i:myint)
{
cout << i << " ";
}
cout << endl << myint.size()<<endl;
for (auto i : mychar)
{
cout << i << " ";
}
cout << endl << mychar.size() << endl;
showall(myint);
showall(mychar);
cin.get();
}
<img src="https://img-blog.csdn.net/20150822232541985?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
template<class T1, class T2>
void showall2(vector<T1>v, list<T2>l)//模板的嵌套 vector与list均为模板
{
vector<vector<T1>>v1;//二维数组
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
for (auto i : l)
{
cout << i << " ";
}
cout << endl;
}
void main()
{
vector<int>myint{ 2, 0, 1, 4, 99 };//vector也是个模板
vector<char>mychar{ 'r', 'o', 'c', 'k', 'e', 't' };
list<int>mylist{ 2, 0, 1, 5, 0 };
list<char>mylistchar{ 'z', 'r', 'f'};
showall2(myint, mylistchar);//模板的嵌套
showall2(mychar, mylist);
cin.get();
}
int add(int a, int b)
{
return a + b;
}
template <class T,class F>
T run(T t1,T t2 , F f)
{
return f(t1, t2);
}
void main()
{
function<int(int, int)>fun = add;//包装函数
function<int(int, int)>fun2 = [](int a, int b)->int{return a - b; };//->int 指明返回值为int型
cout << fun(12,3) << endl;
cout << run(23, 34, fun) << endl;
cout << run<int>(23, 34, fun) << endl;
cout << run<int, function<int(int, int)>>(12.34, 34.56, fun) << endl;
cin.get();
}
更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。
关于公众号的描述访问如下链接