一、typename的使用场合
1.在模板定义里,表明其后的模板参数是类型参数
typename
template<typname T, int a, int b> //typename 后边跟的是一个类型
int funcaddv2(T c){…}
类模板
template //名字为 T 的模板参数。这个虽然可以用 class,但是这里的 class 不是类定义的意思,不能和类定义时的 class 混为一谈。
class myvector {…};
typename可以写为class
- 使用类的类型成员,用 typename 来标识这是一个类型
::作用域运算符访问类中的静态成员的时候,类名::静态成员名
int Time::myststix = 5;
::还可以用来访问类型成员
typename 的第二个用法;通知编译器,一个名字代表的是一个类型。这里的typename不能换成class
template<typename T>
//typename的必须性,目的是显式通知编辑器myiterator是个类型
// 访问类型成员myiterator
// 这里的typename不能换成class
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();
}
int main()
{
string mytest = "hello";
string::size_type size1 = mytest.size(); //string::size_type类似于unsigned int
string::size_type size2 = getLength(mytest);
cout << size1 << endl;
cout << size2 << endl;
return 0;
}
二、函数指针做其他函数的参数
//把函数指针作为函数参数传递需要:
typedef int (*FunType)(int,int); //定义函数指针类型
int my(int t1,int t2)
{
return t1+t2;
}
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)
{
count << funcpoint(i,j) << endl;
}
int main()
{
testFunc(2,3,my);//函数指针做其他函数的参数
return 0;
}
三、函数模板趣味用法举例
class tc
{
public:
tc()
{
cout << "构造函数执行" << endl;
}
tc(const tc& t)
{
cout << "拷贝构造函数执行" << endl;
}
~tc()
{
cout << "析构函数执行" << endl;
}
public:
int operator()(int i, int j)
{
return i + j;
}
};
template<typename T, typename F>
void testfunc(const T& i, const T& j, F funcpoint)
{
int result = funcpoint(i, j);
cout << result << endl;
}
int main()
{
testfunc(5, 10, mf);
tc tcobj;
//testfunc(5, 10, tcobj);
testfunc(5, 10, tc());
cout << tc()(1, 2) << endl;
return 0;
}
四、默认模板参数
- 类模板,类模板名后面必须用<>来提供额外的信息,<>表示这是一个模板
template<typename T = int, int size = 10>
class myarrary
{
public:
myarrary()
{
cout << "myarrary()" << endl;
cout << size << endl;
};
myarrary(T arr)
{
cout << "myarrary(T arr)" << endl;
cout << size << endl;
}
};
int main()
{
myarrary<> arr1; //完全用模板参数的缺省值
myarrary<int> arr2; //提供一个非缺省值,只提供一个,另外一个(第二个参数)用的是缺省值
return 0;
}
- 函数模板:老标准只能为类模板提供默认的模板参数,c++11新标准可以为函数模板提供默认参数。
typedef int(*FuncType)(int, int);
int mf(int tmp1, int tmp2)
{
return tmp1 + tmp2;
}
class tc
{
public:
tc()
{
cout << "构造函数执行" << endl;
}
tc(const tc& t)
{
cout << "拷贝构造函数执行" << endl;
}
~tc()
{
cout << "析构函数执行" << endl;
}
public:
int operator()(int i, int j)
{
return i + j;
}
};
//template<typename T, typename F = tc>
//void testfunc(const T& i, const T& j, F funcpoint = F())
//{
// int result = funcpoint(i, j);
// cout << result << endl;
//}
template<typename T, typename F = FuncType>
void testfunc(const T& i, const T& j, F funcpoint = mf)
{
int result = funcpoint(i, j);
cout << result << endl;
}
int main()
{
testfunc(3, 4);
return 0;
}
(1)同时给模板参数和函数参数提供缺省值;
(2)注意写法F funcpoint = F();
(3)tc重载()。