簡體   English   中英

C ++將Lambda函數作為類構造函數參數傳遞

[英]C++ pass Lambda function as Class constructor argument

我正在使用Visual Studio2015。我的問題是,當我運行它時,它會編譯並沒有問題:

typedef double Fct(double);

struct Function {
    Function(Fct f) { cout << f(1) << endl; };
 };

double double_func(double x, double n) { return x + n; }

int main() {
   for(int n = 0; n < 50; ++n)
      Function e{ [](double x) { return double_func(x,1); } }
}

事情是我想要這部分:

Function e{ [](double x) { return double_func(x,1); } }

要具有如下捕獲參數:

typedef double Fct(double);

struct Function {
    Function(Fct f) {};
 };

double double_func(double x, double n) { return x + n; }

int main() {
   for(int n = 0; n < 50; ++n)
      Function e{ [n](double x) { return double_func(x,n); } }
}

但是我遇到了這個錯誤: no instance of constructor "Function::Function" matches the argument list argument types are: (lambda []double (double x)->double)

編輯:刪除了示例1.不再起作用。 :(

Lambda實際上是一個帶有operator()實現的類。 如果要保存捕獲的對象,則必須將其存儲為對象函數指針:

int first = 5;
auto lambda = [=](int x, int z) {
    return x + z + first;
};
int(decltype(lambda)::*ptr)(int, int)const = &decltype(lambda)::operator();
std::cout << "test = " << (lambda.*ptr)(2, 3) << std::endl;

如果要返回此函數並從其他位置執行它。 (lambdas實際上是可能的)您必須保存對象:

// OT => Object Type
// RT => Return Type
// A ... => Arguments
template<typename OT, typename RT, typename ... A>
struct lambda_expression {
   OT _object;
   RT(OT::*_function)(A...)const;

   lambda_expression(const OT & object)
      : _object(object), _function(&decltype(_object)::operator()) {}

   RT operator() (A ... args) const {
      return (_object.*_function)(args...);
   }
};

auto capture_lambda() {
  int first = 5;
  auto lambda = [=](int x, int z) {
    return x + z + first;
  };
  return lambda_expression<decltype(lambda), int, int, int>(lambda);
}

Fct不是您要傳遞的Lambda的超類型。 (大概是因為函數指針比這種lambda占用更少的存儲空間)您可能想將std::function<...>用作Fct的類型,而不是使用typedef函數指針。

暫無
暫無

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

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