C++ resolves the required parameter of recommended based on the function pointer passed in

  • 2020-06-03 07:54:19
  • OfStack

C++ can get the parameter type it needs according to the function pointer passed in, and then get the parameter type it needs according to the parameter source. Here I use tuple as a demonstration. However, as long as you can get the argument according to the ordinal number, or the sequential way, etc., you can use a similar way to achieve:

First, an auxiliary function is given:

/**  For the first N A type of 
template <typename... Cases>
struct select
template <typename T, typename... Cases>
struct select<T, Cases...> : public select<Cases...>
  using ThisType = T;
  using Base = select<Cases...>;

The actual implementation function is given below:

#include <functional>
#include "vs-help.h"

class TupleFunc
  TupleFunc() { }

  //  The actual construction of a function 
  template <typename Ret, typename... Args, typename ParamsSource>
  void makeFuncAndParams(Ret(*func)(Args...), ParamsSource& paramSource)
    makeFuncAndParamsImpl<0>(func, select<Args...>(), paramSource);

  //  The actual call 
  void invoke() 

  //  The actual call is initialized 
  template <size_t idx, typename Func, typename Select, typename ParamsSource, typename... Params>
  void makeFuncAndParamsImpl(Func&& func, Select, ParamsSource& paramSource, Params&&...args)
    typename Select::ThisType param = std::get<idx>(paramSource);
    makeFuncAndParamsImpl<idx + 1>(func, Select::Base(), paramSource, std::forward<Params>(args)..., std::move(param));
  //  The end of the call 
  template <size_t idx, typename Func, typename ParamSource, typename... Params>
  void makeFuncAndParamsImpl(Func&& func, select<>, ParamSource& paramSource, Params&&... args)
    m_func = [func, args...]() { func(args...); };
  std::function<void()> m_func;

Here are the test cases:

void print(int x, std::string y)
  std::cout << "x: " << x << std::endl;
  std::cout << "y: " << y << std::endl;
int main()
  std::tuple<int, std::string, std::string> p = { 12, "job", "China" };
  TupleFunc func;
  func.makeFuncAndParams(&print, p);
  return 0;

By using the lambda expression, we can easily build a function we need to call, and the existence of templates, we can build a lambda expression, can be dynamic, in some cases, more flexible to build various processing functions map. The above is just a simple demonstration. In the specific scenario, 1 definite modification is needed.


Above is the site to you to introduce C++ according to the passed function pointer to resolve the need for parameters, I hope to help you, if you have any questions welcome to leave a message, this site will promptly reply you!

Related articles: