//////////////////////////////////////////////////////////////////
// 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);
}
私はそれが醜いことを知っています。ラムダは、最初にここで実験するときに使用することを目的としているため、実際には使用しません。何らかの理由で文字列変数の入力が得られず、その理由がわかりません。誰かが問題が何であるかを助ける/指摘することができますか?