Is that possible to have a function with function as its parameter?

I have see function can have variable, address, and class as its parameter, but is it possible for a function to use function as parameter? Like:

1
2
3
4
5
Int func1(n){int func1n = n)

Int func2(func1){
........
}


Is that possible?
Not that I know of. Why on Earth would you want to do that?
Just wonder if this could have its unique uses.
Yes, a function can take a function pointer as argument.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int func1(int n)
{
	return n * n;
}

void func2(int (*func)(int)) 
{
	for (int i = 0; i < 5; ++i)
	{
		std::cout << func(i) << std::endl;
	}
}
int main()
{
	func2(func1);
}


If you want you can typedef the function type to make it easier to write.
1
2
3
4
5
typedef int (*FunType)(int);

void func2(FunType func)
{
	...


In C++11 you can also use the class template std::function.
1
2
3
void func2(std::function<int(int)> func)
{
	...
This allows you to not only pass functions but also lambda expressions, bind expressions and other functors.
Last edited on
Topic archived. No new replies allowed.