Home > Software design >  why std::function is not executed
why std::function is not executed

Time:12-18

I am using std::bind to create a std::function type and typedef it, but its instance would not execute. Following is my code:

void func(int a, const std::string& b)
{
    std::cout << a << ", " << b << std::endl;
}
typedef std::function<void (int, const std::string&)> THE_FUNCTION;

THE_FUNCTION f = std::bind(func, 18, std::string("hello world"));

f; // no action at all
f(); // will not compile, term does not evaluate to a function taking 0 arguments
     // class does not define an 'operator()' or a user defined conversion operator 
     // to a pointer-to-function or reference-to-function that takes appropriate number 
     // of arguments
f.operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()'
              // : non-standard syntax; use '&' to create a pointer to member
(&the_f)->operator(); // will not compile, 'std::_Func_class<_Ret,int,const std::string &>::operator ()': non-standard syntax; use '&' to create a pointer to member

But if I do this, then the function will get executed:

auto g = std::bind(func, 3, "good morning")
g()

CodePudding user response:

Change this:

typedef std::function<void (int, const std::string&)> THE_FUNCTION; 

with:

typedef std::function<void ()> THE_FUNCTION; 

and it will work.

L.E.: When you call bind, it means you have a function that "is very similar" with what you want, and fill the rest of the arguments that are not needed with some provided "values".

https://en.cppreference.com/w/cpp/utility/functional/bind

  • Related