我正在使用 Visual Studio 2015。 我的问题是,当我运行它时,它编译并运行没有问题:
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); } }
}
但我收到此错误:没有构造函数“Function::Function”的实例与参数列表参数类型匹配:(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;
如果你想返回这个函数并从其他地方执行它。 (这实际上可以通过 lambda 实现)你必须保存对象:
// 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);
}
关于C++ 将 Lambda 函数作为类构造函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41903979/