简体   繁体   English

如何在 C++ lambda 中捕获 function

[英]How to capture a function in C++ lambda

I'm wondering how I can pass a function in the capture list.我想知道如何在捕获列表中传递 function 。 My code snippet is shown below.我的代码片段如下所示。 It aborts with error: capture of non-variable 'bool isVowel(char)' .它因error: capture of non-variable 'bool isVowel(char)'

Why does this similar posted solution with a function pointer work?为什么这个带有 function 指针的类似发布解决方案有效?

#include <iostream>
#include <algorithm>
#include <set>
#include <list>
using namespace std;

bool isVowel(char c){
  string myVowels{"aeiouäöü"};
  set<char> vowels(myVowels.begin(), myVowels.end());
  return (vowels.find(c) != vowels.end());
}

int main(){
  list<char> myCha{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
  int cha[]= {'A', 'B', 'C'};
  // it doesn't work
  auto iter = adjacent_find(myCha.begin(), myCha.end(),
                           [isVowel](char a, char b){ return isVowel(a) == isVowel(b); 
});
  if (iter != myCha.end()) cout << *iter;
    
}

Why does this similar snippet work?为什么这个类似的片段有效?

Because in that snippet:因为在那个片段中:

auto func(void(*func2)())
{
    return [&func2](){cout<<"hello world 1"<<endl;func2();};
}

func2 is a local variable with type pointer to a function. func2是一个局部变量,其类型指针指向 function。 In your case you are trying to capture a function itself which is not allowed:在您的情况下,您试图捕获 function 本身,这是不允许的:

The identifier in any capture without an initializer (other than the this-capture) is looked up using usual unqualified name lookup in the reaching scope of the lambda.在 lambda 的到达 scope 中,使用通常的非限定名称查找来查找没有初始化程序(除了 this-capture)的任何捕获中的标识符。 The result of the lookup must be a variable with automatic storage duration declared in the reaching scope , or a structured binding whose corresponding variable satisfies such requirements (since C++20).查找的结果必须是在到达 scope 中声明的具有自动存储持续时间的变量,或者其对应变量满足此类要求的结构化绑定(C++20 起)。 The entity is explicitly captured.实体被显式捕获。

from here (emphasis is mine).这里(重点是我的)。 Function name is definitely not a variable with automatic storage duration. Function name 绝对不是自动存储时长的变量。

Not clear why are you trying to capture this function, as it would work without any capture and it does not make any sense (unlike question you point to, where OP wanted to use different function in different case hence he/she captured the pointer).不清楚您为什么要尝试捕获此 function,因为它无需任何捕获即可工作并且没有任何意义(与您指出的问题不同,OP 想在不同的情况下使用不同的 function 因此他/她捕获了指针) .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM