(1) 声明函数指针类型
假设函数CompareSizes定义为:
template<class T>
int CompareSizes(const T& tValue1, const T& tValue2)
{
return (tValue1 > tValue2) ? 1 : ((tValue1 == tValue2) ? 0 : -1);
}
要想定义CompareSizes的函数指针类型,有两种方式,typedef和using,最简单的就是用decltype:
//定义函数指针类型
using pCompareSizesType = decltype(&CompareSizes);
/// <summary>
/// 比较两个对象的大小
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tValue1"></param>
/// <param name="tValue2"></param>
/// <returns></returns>
template<class T = int>
int CompareSizes(const T& tValue1, const T& tValue2)
{
return (tValue1 > tValue2) ? 1 : ((tValue1 == tValue2) ? 0 : -1);
}
int main()
{
//声明pCompareSizesType1是指向函数指针类型
using pCompareSizesType1 = decltype(&CompareSizes<string>);
//声明pCompareSizesType2是指向函数指针类型
typedef int (*pCompareSizesType2)(const string& tValue1, const string& tValue2);
//pf是指向CompareSizes的变量
int (*pf)(const string & tValue1, const string & tValue2) = &CompareSizes<string>;
pCompareSizesType1 pf1;
pCompareSizesType1 pf2;
pf1 = pf; //正确,相同类型赋值
pf2 = pf; //正确,相同类型赋值
pf("1", "2"); //调用CompareSizes<string>("1", "2");
pf1("1", "2"); //调用CompareSizes<string>("1", "2");
pf2("1", "2"); //调用CompareSizes<string>("1", "2");
return 0;
}
(2) 在函数中用函数指针作为函数参数。
/// <summary>
/// 比较两个对象的大小
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tValue1"></param>
/// <param name="tValue2"></param>
/// <returns></returns>
template<class T = int>
int CompareSizes(const T& tValue1, const T& tValue2)
{
return (tValue1 > tValue2) ? 1 : ((tValue1 == tValue2) ? 0 : -1);
}
//声明pCompareSizesType1是指向函数指针类型
using pCompareSizesType1 = decltype(&CompareSizes<string>);
//声明pCompareSizesType2是指向函数指针类型
typedef int (*pCompareSizesType2)(const string& tValue1, const string& tValue2);
// 等价于test1(pCompareSizesType1 pf)
void test1(const string& s1, decltype(&CompareSizes<string>) pf)
{
}
//这里直接声明函数指针
template<class T = int>
void test2(const T& t1, int CompareSizes(const T& tValue1, const T& tValue2))
{
}
void test3(const string& s, pCompareSizesType1 pf)
{
}
int main()
{
//调用函数testg1
test1("a", [](const string& s1, const string& s2)->int{
return 0;
});
//调用函数test2<int>
test2<int>(5, [](const int& i1, const int& i2)->int {
return 0;
});
//调用函数test3
test3("a", [](const string& s1, const string& s2)->int {
return 0;
});
return 0;
}
最后,你还可以使用用auto关键,例:
auto pf = &CompareSizes<int>;
auto pf = &CompareSizes<string>;