c++11模板:获取函数的参数类型

假设我们已经知道一个函数类型的定义double(unsigned char*, unsigned char*),如何获取这个函数定义中的输入和输出参数类型呢?
c++11提供的模板函数std::functionstd::tuple_element可以将一个函数定义的输入和输出参数类型一个一个解析出来,下面是实现代码

#include <functional>
#include <tuple>

#include <windows.h>
#include "FSFaceSDK.h"
template<typename T> 
struct function_traits;  
// R为返回类型
// ...Args 为输入参数类型,个数不限
template<typename R, typename ...Args> 
struct function_traits<std::function<R(Args...)>>
{
    static const size_t nargs = sizeof...(Args);
	// 返回类型
    typedef R result_type;

	// 输入参数类型,i为从0开始的参数类型索引
    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
    };
};
inline double compare(const face_code &f1,const face_code&f2){

	typedef std::function<double(unsigned char*, unsigned char*)> feacomp_fun;
	return (double)FSCompare(
		/* 强制类型转换为function_traits<feacomp_fun>::arg<0>::type,第一个输入参数类型 */
		(function_traits<feacomp_fun>::arg<0>::type)f1.element,	
		/* 强制类型转换为function_traits<feacomp_fun>::arg<1>::type,第一个输入参数类型 */
		(function_traits<feacomp_fun>::arg<1>::type)f2.element);
}

参考资料
https://stackoverflow.com/questions/9065081/how-do-i-get-the-argument-types-of-a-function-pointer-in-a-variadic-template-cla
https://en.cppreference.com/w/cpp/utility/functional/function
https://en.cppreference.com/w/cpp/utility/tuple/tuple_element

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值