溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++根據(jù)傳入的函數(shù)指針來解析需要的參數(shù)(推薦)

發(fā)布時間:2020-10-16 01:09:09 來源:腳本之家 閱讀:95 作者:月落無影 欄目:編程語言

C++可以根據(jù)傳入的函數(shù)指針,獲取自己需要的參數(shù)類型,然后根據(jù)參數(shù)源中獲取需要的參數(shù),這里我用tuple作為演示,不過,只要可以根據(jù)序號,或者順序方式等獲取實參,都可以使用類似的方式實現(xiàn):

先給出一個輔助函數(shù):

/** 獲取第N個類型
*/
template <typename... Cases>
struct select
{
};
template <typename T, typename... Cases>
struct select<T, Cases...> : public select<Cases...>
{
  using ThisType = T;
  using Base = select<Cases...>;
};

下面給出實際的實現(xiàn)函數(shù):

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

class TupleFunc
{
public:
  TupleFunc() { }

  // 函數(shù)的實際構(gòu)造過程
  template <typename Ret, typename... Args, typename ParamsSource>
  void makeFuncAndParams(Ret(*func)(Args...), ParamsSource& paramSource)
  {
    makeFuncAndParamsImpl<0>(func, select<Args...>(), paramSource);
  }

  // 實際調(diào)用
  void invoke() 
  {
    m_func();
  }

private:
  // 實際調(diào)用初始化
  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));
  }
    
  // 結(jié)束調(diào)用
  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...); };
  }
private:
  std::function<void()> m_func;
};

下面是測試用例:

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);
  func.invoke();
  return 0;
}

通過使用lambda表達式,我們可以很方便的構(gòu)建一個我們調(diào)用時需要的函數(shù),而模板的存在,可以使我們在構(gòu)建一個lambda表達式的時候,可以動態(tài)化,使某些情況下,更加靈活的構(gòu)建各類處理函數(shù)map等。上面只是簡單的演示,具體場景下,需要進行一定的修改。

總結(jié)

以上所述是小編給大家介紹的C++根據(jù)傳入的函數(shù)指針來解析需要的參數(shù),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI