Whats the difference between std::function<> and a standard function pointer?
that is:
typedef std::function<int(int)> FUNCTION;
typedef int (*fn)(int);
Are they effectively the same thing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A function pointer is the address of an actual function defined in C++. An
std::functionis a wrapper that can hold any type of callable object (objects that can be used like functions).Here,
std::functionallows you to abstract away exactly what kind of callable object it is you are dealing with — you don’t know it’sFooFunctor, you just know that it returnsvoidand has oneintparameter.A real-world example where this abstraction is useful is when you are using C++ together with another scripting language. You might want to design an interface that can deal with both functions defined in C++, as well as functions defined in the scripting language, in a generic way.
Edit: Binding
Alongside
std::function, you will also findstd::bind. These two are very powerful tools when used together.In that example, the function object returned by
bindtakes the first parameter,_1, and passes it tofuncas theaparameter, and setsbto be the constant5.