假设我们已经知道一个函数类型的定义double(unsigned char*, unsigned char*)
,如何获取这个函数定义中的输入和输出参数类型呢?
c++11提供的模板函数std::function
和std::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