005typename的应用场合_用在模板函数类型成员前表示是一个类型
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
using namespace std;
template<typename T>
typename T::size_type GetLength(const T&c)
{
if (c.empty())
{
return 0;
}
return c.size();
}
int main(void)
{
string mytest = "jisuanjizuchegnyuanli";
string::size_type size = GetLength(mytest);
system("pause");
return 0;
}
006函数指针调用函数
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
using namespace std;
int myFunction(int a,int b)
{
return a + b;
}
typedef int(*FunType)(int, int);
void TestFunction(int i,int j,FunType myfun)
{
int result = myfun(i, j);
cout << result << endl;
}
int main(void)
{
TestFunction(1, 2, myFunction);
TestFunction(1, 2, &myFunction);
system("pause");
return 0;
}
007函数模板趣味用法_传递一个可调用类对象作为类模板参数
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
using namespace std;
int myFunction(int a, int b)
{
return a + b;
}
typedef int(*FunType)(int, int);
template <typename T,typename F>
void testFunction(const T&i,const T&j,F myfunc)
{
cout << myfunc(i, j) << endl;
}
class tc
{
public:
tc()
{
cout << "无参构造函数执行" << endl;
}
tc(const tc&t)
{
cout << "拷贝构造函数执行" << endl;
}
int operator()(int a,int b)
{
return a + b;
}
public:
};
int main(void)
{
testFunction(1, 2,myFunction);
tc object01;
testFunction(3, 4, object01);
cout << "_______________________________" << endl;
testFunction(5, 6, tc());
system("pause");
return 0;
}
008默认模板参数
#include<iostream>
#include<cstdlib>
#include<string>
#include<vector>
#include"myArray.h"
using namespace std;
int myFunction(int a, int b)
{
return a + b;
}
typedef int(*FunType)(int, int);
template <typename T, typename F=FunType>
void testFunction(const T&i, const T&j, F myfunc=myFunction)
{
cout << myfunc(i, j) << endl;
}
int main(void)
{
myArray<> my_array01;
myArray<int >my_array02;
testFunction(3, 4);
system("pause");
return 0;
}