0

I'm trying to create a list of function pointers, and these functions is passed as lambda.

    string msg = "hello";
    vector<string (*)() > myvector;
    auto f = [=]() -> string {return msg; };
    myvector.push_back(f);
    cout << (*myvector[0])();

However, I got error in compiling when tried to capture variable and it successed when i didn't capture anything. This problem occur when i use map, pair or sth similar.

funtionPointer.cc:36:22: error: no matching function for call to ‘std::vector<std::__cxx11::basic_string<char> (*)()>::push_back(main()::<lambda()>&)’
  myvector.push_back(f);

Thank for any help.

1 Answers1

0

C++ makes a distinction between types for function pointers and types for lambdas that have capture lists. The lambda you've made is callable as a function, but its type isn't "pointer to a function taking no arguments and returning void." More specifically, the type of that lambda expression will be some anonymous object type.

If you want to store a list of objects that can be called as a function that takes in no arguments and returns a string, consider making a vector of std::function<string()>, which can store a wider assortment of types callable as functions.

If you do this, to call those functions, you'd use the syntax

cout << myvector[0]() << endl;

rather than

cout << *(myvector[0])() << endl;

as you're no longer storing function pointers. (Fun fact - you don't actually have to dereference function pointers to call them!)

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065