0

What's the use of function provided by functional header

Hi Below is sample code on function from functional header: https://code.sololearn.com/ce4iRZuzC3wl/?ref=app I know it's very basic code..but in such case, we could directly have called function add instead of using f to call same. What is that which helps and suits need of function from functional header? Why it's introduced.. p.s. updated code with two functions add and sub getting assigned to same f... But this is possible by function pointer aslo...

18th Jun 2020, 10:03 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Antworten
0
std::function allows you to create a valid function type that can be passed as a template argument. For instance,a priority_queue requires a comparator(either a function or a function object) as its first argument. Let's consider a case where you have a function like this bool f(int a,int b){return a>b;} You want this to be your comparator instead of the default less(<) This is what you will do priority_queue<int,vector<int>,function<decltype(f)>> q{f,V}//V is a vector<int> object Note that the code below will not work (even though it seems sensible) priority_queue<int,vector<int>,decltype(f)> q{f,V}; since in that case priority_queue's definition will be declaring a function as a variable which is not allowed in C++. Thus think of std::function as a wrapper for functions that produces a valid type for the function it holds
19th Jun 2020, 11:04 AM
Anthony Maina
Anthony Maina - avatar
0
Its quite useful when you want to pass a function type as a template argument
19th Jun 2020, 8:05 AM
Anthony Maina
Anthony Maina - avatar
0
Ii could not understand phrase function types as a template argument. We can provide type as template argument like int, double etc.What is the meaning of function type as template argument?
19th Jun 2020, 10:43 AM
Ketan Lalcheta
Ketan Lalcheta - avatar