繁体   English   中英

如何在 C++ lambda 中捕获 function

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

我想知道如何在捕获列表中传递 function 。 我的代码片段如下所示。 它因error: capture of non-variable 'bool isVowel(char)'

为什么这个带有 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;
    
}

为什么这个类似的片段有效?

因为在那个片段中:

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

func2是一个局部变量,其类型指针指向 function。 在您的情况下,您试图捕获 function 本身,这是不允许的:

在 lambda 的到达 scope 中,使用通常的非限定名称查找来查找没有初始化程序(除了 this-capture)的任何捕获中的标识符。 查找的结果必须是在到达 scope 中声明的具有自动存储持续时间的变量,或者其对应变量满足此类要求的结构化绑定(C++20 起)。 实体被显式捕获。

这里(重点是我的)。 Function name 绝对不是自动存储时长的变量。

不清楚您为什么要尝试捕获此 function,因为它无需任何捕获即可工作并且没有任何意义(与您指出的问题不同,OP 想在不同的情况下使用不同的 function 因此他/她捕获了指针) .

暂无
暂无

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

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