有关C++的函数指针(typedef, using, decltype, auto)的一些技巧。

(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>;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值