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; }
source share