实例代码:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class myvector{
public:
typedef T* myiterator;
public:
myvector();
myvector& operator=(const myvector&);
public:
myiterator mybegin();
myiterator myend();
public:
void myfunc();
};
template<typename T>
void myvector<T>::myfunc(){
return;
}
template<typename T>
myvector<T>::myvector(){
}
template<typename T>
myvector<T>& myvector<T>::operator=(const myvector&){
return *this;
}
template<typename T>
typename myvector<T>::myiterator myvector<T>::mybegin(){
}
template<typename T>
typename T::size_type getlength(const T&c){
if (c.empty())
return 0;
return c.size();
}
typedef int(*FunType)(int, int);
int mf(int tmp1, int tmp2){
return 1;
}
void testfunc(int i, int j, FunType funcpoint)
{
int result = funcpoint(i, j);
cout << result << endl;
}
template<typename T, typename F>
void testfunc(const T &i, const T &j, F funcpoint){
cout << funcpoint(i, j) << endl;
}
class tc{
public:
tc() { cout << "构造函数执行" << endl; }
tc(const tc& t) { cout << "拷贝构造函数执行" << endl; }
int operator()(int v1, int v2)const{
return v1 + v2;
}
};
template<typename T, typename F = tc>
void testfuncv1(const T &i, const T &j, F funcpoint = F()){
cout << funcpoint(i, j) << endl;
}
template<typename T, typename F = FunType>
void testfuncv2(const T &i, const T &j, F funcpoint = mf){
cout << funcpoint(i, j) << endl;
}
template<typename T = string, int size = 10>
class myarray{
private:
T arr[size];
public:
void myfunc();
};
template<typename T, int size>
void myarray<T, size>::myfunc()
{
cout << size << endl;
return;
}
int main()
{
string mytest = "I Love China!";
string::size_type size = getlength(mytest);
testfunc(3, 4, mf);
tc tcobj;
testfunc(3, 4, tcobj);
testfunc(3, 4, tc());
myarray<> abc;
myarray<int> def;
testfuncv1(3, 4);
system("pause");
}