How can I capture some (but not all) member variables of a class with C ++ lambda

The following dummy example may not make sense in the real world. But that explains the question. I have a class Foo with elements firstname and lastname . The ForEachMessage function accepts a lambda. I want him to write down only firstname from Foo , but not lastname . How do I achieve this?

 #include <iostream> #include <vector> #include <functional> using namespace std; vector<string> messagesList; void ForEachMessage(function<void(const string&)>callBack) { for (const auto& str : messagesList) { callBack(str); } } class Foo { public: std::string firstname; std::string lastname; void say() { ForEachMessage([this](const std::string& someMessage) { cout << firstname << ": " << someMessage << endl; }); // Error: firstname in capture list doesn't name a variable // ForEachMessage([firstname](const std::string& someMessage) // { // cout << firstname << ": " << someMessage << endl; // }); // Error: expect ',' or ']' in lambda capture list // ForEachMessage([this->firstname](const std::string& someMessage) // { // cout << firstname << ": " << someMessage << endl; // }); } }; int main(int argc, const char * argv[]) { Foo foo; foo.firstname = "Yuchen"; foo.lastname = "Zhong"; messagesList.push_back("Hello, World!"); messagesList.push_back("Byebye, World!"); foo.say(); return 0; } 
+5
source share
2 answers

You can use captured C ++ 14 for this:

 ForEachMessage([bla=firstname](const std::string& someMessage) { cout << bla << ": " << someMessage << endl; }); 

(See live ) To avoid copying, you can also grab the link [&bla=firstname] . For a discussion of how to capture const& , see this question and, in particular, this answer .

(Note. The local name may, but should not, be different from the participant’s name.)

+5
source

Create a link to firstname

 const std::string& rfn = firstname; 

And write down the link

 ForEachMessage([rfn](const std::string& someMessage) { cout << rfn << ": " << someMessage << endl; } 
+3
source

Source: https://habr.com/ru/post/1244237/


All Articles