//////////////////////////////////////////////////////////////////
// Capture a lambda with a lambda and use it in the lambda it's //
// captured in along with some code in the lambda that captures //
// it. //
// //
// Add to that to capture a variable in the client and use that //
// too. //
// //
// Then make a lambda that captures a class object and calls //
// some method or methods with it, optionally modifies the re- //
// sult... //
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Note: std::function<type(type)> f; //
// f = <define lambda here> //
// f() //calls lambda //
//////////////////////////////////////////////////////////////////
#include <functional>
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::function;
using std::getline;
using std::string;
class Experimental {
private:
int x;
string s;
public:
Experimental() {}
~Experimental() {}
void set_x(int new_x);
int get_x();
void set_s(string s_in);
string get_s();
};
void Experimental::set_x(int new_x) {
x = new_x;
}
int Experimental::get_x() {
return (x);
}
void Experimental::set_s(string s_in) {
s = s_in;
}
string Experimental::get_s() {
return s;
}
int main() {
double n;
string input;
Experimental* experiment = new Experimental();
cout << "Enter a number: ";
cin >> n;
function<double(double)> f;
f = [&f](double k) {
return (k ? k * f(k-1) : 1);
};
function<double(double)> g;
g = [&f,n](double m) {
return (f(n)/n);
};
function<int()> T1; //capture a class and do stuff...
T1 = [&experiment,n]() {
experiment->set_x(13 + n);
int m = experiment->get_x();
return (m);
};
function<string(string)> T2; //capture a class and do stuff...
T2 = [&experiment](const string in) {
experiment->set_s(in);
string s = experiment->get_s();
return (s);
};
cout << "The factorial of " << n << " is: ";
cout << f(n) << endl;
cout << "The factorial of " << n << " divided by " << n << " is: ";
cout << g(n) << endl;
cout << "The new value of x in experiment is: ";
cout << T1() << endl;
cout << "Enter a string: ";
getline(cin, input); //FIXME
cout << "input is: " << input << "<-" << endl;
cout << "The new string in experiment is: ";
cout << T2(input) << endl;
delete experiment;
return (0);
}
我知道这很丑。没有真正使用 lambda,因为我最初在这里进行实验时应该使用它们。出于某种原因,我没有得到我的字符串变量的输入,我也不知道为什么。有人可以帮助/指出问题所在吗?