簡體   English   中英

將C ++模板與std :: function和std :: bind一起使用

[英]Using C++ template with std::function and std::bind

我正在嘗試創建一個模板類,該模板類又將在函數上生成包裝器。 然后,該類將返回包裝器作為結果。 我想使用模板來具有通用類,該通用類可與具有不同簽名的任何函數一起使用,例如:

  1. std::function<void()>task = std::bind(fun1, param1, param2);
  2. std::function<int(int, int)>task = std::bind(fun2, param1, param2);

我想要這樣的東西:

template <typename T1, typename T2>
class A {
  A (string param1, string param2) {
    // The created wrapper here i.e. 'task' will be returned by the class.
    function<T1>task = bind(T2, param1, param2);
  }

  // Return the created wrapper in the constructor.
  function<T1> returnWrapper() {
    return task;
  }
};

上面的代碼大部分是偽代碼,因為它無法編譯,但可以讓我對所要查找的內容有所了解。 有什么解決辦法嗎? 我認為應該不僅僅是為函數簽名使用模板。 任何幫助將不勝感激。 我還希望能夠在可能的情況下將任意數量的參數傳遞給“綁定”。

我想我解決了問題! 我必須定義一個類,該類在模板內使用兩個類型名稱,並將其中一個類型名稱傳遞給std :: function,作為函數簽名,然后在構造函數中使用第二個名稱在std中定義curried函數(包裝后的結果函數) :: bind。 然后一切正常! 可能有一些更好的解決方案,但這是我得到的最好的或差不多的清晰解決方案。 這是我找到的解決方案的摘要! 希望它對其他問題有幫助:

#include <iostream>
#include <functional>

using namespace std;

class A {
  private:
    template <typename T1, typename T2>
    class B { 
      private:
        function<T1>ff;

      public:
        B(T2 fun) {
          ff = bind(fun, 1, placeholders::_1);
        }

        virtual ~B() {
        }

        int exec(int x) {
          return ff(x);
        }
    };

    static int myFun(int x, int y) {
      return x + y;
    }

  public:
    A() { 
    };

    int test() {
      B<int(int), int (*)(int, int)> b(&myFun);
      return b.exec(10);
    }

    virtual ~A() {
    };
};

int main() {
  A a;

  // Correct result is '11' since we pass 11 and 1 is in the curried function.
  cout << "test result: " << a.test() << endl;

  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM