Is it possible to pass the name of a function(say A) as an argument to another function (say B), and then call function A from function B. That is the function name will be stored in a variable in B, and using it call the function whose name is in the variable. For Example in C++ sort function the first and second arguments are iterators, but the third argument is the name of a function.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.
In Python, just like a normal variable, we can pass a user-defined function as an argument to another function. A function that accepts another function as its parameter is called a Higher-order function.
Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
You can introduce a template parameter (here Pred
) for "anything that is callable with two parameters":
template <typename Iter, typename Pred>
void mysort(Iter begin, Iter end, Pred predicate)
{
--end;
// ...
if (predicate(*begin, *end))
{
// ...
}
// ...
}
Then you can pass either good old C function pointers or C++ function objects:
bool function(int x, int y)
{
return x < y;
}
struct function_object
{
bool operator()(int x, int y)
{
return x < y;
}
};
int main()
{
int numbers[] = {543, 6542654, 432514, 54, 45, 243};
mysort(numbers + 0, numbers + 6, &function);
mysort(numbers + 0, numbers + 6, function_object());
}
As you can see, a function object is an object of a class that overloads operator()
appropriately.
You should read up on Function Pointers.
simple example with Function Pointers:
#include <iostream>
int apply(int (*fun)(int,int), int a, int b) {
return (*fun)(a,b);
}
int add(int a, int b) {return a + b;}
int multiply(int a, int b) {return a * b;}
int main(int argc, const char* argv[]) {
int added = apply(add, 2, 4);
int multiplied = apply(multiply, 2, 4);
std::cout << "added result: " << added << std::endl;
std::cout << "multiplied result: " << multiplied << std::endl;
}
output:
added result: 6
multiplied result: 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With