Home > Software engineering >  How to capture a function in C lambda
How to capture a function in C lambda

Time:09-01

I'm wondering how I can pass a function in the capture list. My code snippet is shown below. It aborts with error: capture of non-variable ‘bool isVowel(char)’.

Why does this similar posted solution with a function pointer work?

#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;
    
}

CodePudding user response:

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. In your case you are trying to capture a function itself which is not allowed:

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. 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). The entity is explicitly captured.

from here (emphasis is mine). Function name is definitely not a variable with automatic storage duration.

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).

PS according to your comment you did not understand main reason of error here. Consider these 2 snippets:

int i = 0;

int main() {
    auto f = [i]() {}; // illegal, should fail to compile
}

vs this:

int main() {
    int i = 0;
    auto f = [i]() {}; // should compile fine
}

First snippet is incorrect (though gcc may compile it with warning), second one is just fine.

  •  Tags:  
  • c
  • Related