C++ 如何用C++;兰姆达
下面的虚拟示例在现实世界中可能没有真正意义。但它解释了这个问题。我有一个C++ 如何用C++;兰姆达,c++,C++,下面的虚拟示例在现实世界中可能没有真正意义。但它解释了这个问题。我有一个Foo类,成员包括firstname和lastname。函数ForEachMessage采用lambda。我希望它只捕获Foo的firstname,而不是lastname。我如何做到这一点 #include <iostream> #include <vector> #include <functional> using namespace std; vector<string>
Foo类
,成员包括firstname
和lastname
。函数ForEachMessage
采用lambda。我希望它只捕获Foo
的firstname
,而不是lastname
。我如何做到这一点
#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;
}
#包括
#包括
#包括
使用名称空间std;
向量消息列表;
void ForEachMessage(函数回调)
{
for(const auto&str:messagesList){
回调(str);
}
}
福班{
公众:
std::stringfirstname;
std::字符串lastname;
void say(){
ForEachMessage([this](const std::string&someMessage)
{
无法创建对firstname
const std::string& rfn = firstname;
并捕获引用
ForEachMessage([rfn](const std::string& someMessage)
{
cout << rfn << ": " << someMessage << endl;
}
ForEachMessage([rfn](const std::string&someMessage)
{
cout您可以使用C++14命名的捕获:
ForEachMessage([bla=firstname](const std::string& someMessage)
{
cout << bla << ": " << someMessage << endl;
});
ForEachMessage([bla=firstname](const std::string&someMessage)
{
cout“不起作用”是世界上最不有用的问题描述。@molbdnilo,谢谢你的评论。我还添加了错误消息。。不知道是否有更好的方法。值得一提的是,cherry挑选变量可能不值得努力。编译器可以很好地解决问题,不应该捕获lambda不使用的变量。@BaummitAugen,这很有趣!看起来你甚至可以使用[&firstname=firstname]
@SimonKraemer事实上,你比我的编辑快了几秒。输入的Thx。@BaummitAugen我刚刚测试了是否可以使引用常量
避免在lambda中被更改。[&firstname=static\u cast(firstname)]
完成了这项工作。哎呀。谢谢你修复了我的。M(