北大同学黄雨松昨天讲北太天元插件开发时涉及到函数句柄以及如何传参数

#include <cstdlib>
#include <iostream>
#include <typeinfo>
#include <utility>
using namespace std;
namespace ParseParams {
template <class _T>
class FunTrait;
template <typename R, typename... Args>
class FunTrait<R(Args...)>{
public:
static const size_t n_args = sizeof...(Args);
public:
int required_params;
void **passed_args_ptr;
//变量类型函数句柄, 变量名是decorated_func
R(*decorated_func)
(Args...);
public:
FunTrait(R (*func)(Args...), int num_required = 0){
decorated_func = func;
required_params = num_required;
passed_args_ptr = new void *[n_args] {};
for(size_t i=0;i<n_args;i++){
passed_args_ptr[i] = nullptr;
}
}
template <size_t... I>
R eval_impl(std::index_sequence<I...>){
std::cout<<"需要的参数个数是 = " << required_params << std::endl;
return decorated_func((Args)passed_args_ptr[I]...);
}
R eval(){
return eval_impl(std::make_index_sequence<n_args>());
}
void check_in_args_type(const int * a){
passed_args_ptr[0] = (void *)a;
}
void check_in_args_type(const int * a, const std::string * str){
passed_args_ptr[0] = (void *)a;
passed_args_ptr[1] = (void *)str;
}
};
}
double f(){
std::cout<<" f is a function "<<std::endl;
return 1.0;
}
double g(const int * j){
std::cout<<" *j = "<< *j<<std::endl;
return (double)(*j);
}
char h(const int *j , const std::string *str ){
std::cout<<" *j = "<<*j << std::endl;
std::cout<<" *str = "<<*str << std::endl;
std::cout<<" (*str)[*j] = "<<(*str)[*j]<< std::endl;
return (*str)[*j];
}
int main(){
using namespace ParseParams;
typedef FunTrait<decltype(f)> FT;
//typedef FunTrait<double()> FT;
FT t(f,0);
t.eval();
FunTrait<decltype(g)> s(g,1);
int a = 3;
s.check_in_args_type(&a);
s.eval();
FunTrait<decltype(h)> q(h,2);
std::string str = "LOVE";
int i = 1;
q.check_in_args_type(&i, &str);
q.eval();
return 0;
}