Return Pointer To Function

Aug 24, 2012 at 2:28pm
I am looking to have one function(called F) return a pointer to one of two other functions(F1 and F2). I do not know how the function prototype for F. I have seen something in c, but it used typedefs. Thanks in advance
Aug 24, 2012 at 2:44pm
Do functions F1 and F2 have the same type?
Aug 24, 2012 at 3:10pm
yes, they both return void and take one int argument
Aug 24, 2012 at 3:23pm
1
2
3
4
5
6
7
8
9
10
void one(int) { /* ... */ }
void two(int) { /* ... */ }

decltype(&one) foo( int v ) { return v < 10 ? one : two ; }

typedef void function_type( int ) ;
function_type* bar( int v ) { return v < 10 ? one : two ; }

#include <functional>
std::function< void(int) > baz( int v ) { return v < 10 ? one : two ; }
Aug 24, 2012 at 3:32pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstdlib>
#include <ctime>

void F1(int i)
{
	std::cout << "F1(" << i << ");" << std::endl;
}

void F2(int i)
{
	std::cout << "F2(" << i << ");" << std::endl;
}


void (*F())(int) 
{
	return (rand() & 1 ? F1 : F2);
}

int main()
{
	std::srand(std::time(0));
	void (*f)(int) = F();
	f(7);
}

Aug 24, 2012 at 4:33pm
Thanks Guys, although could you please explain your code:

@Peter what does
 
void (*F())(int)


do?
Aug 24, 2012 at 5:09pm
@Script Coder
It looks a bit weird when having function pointer as return type. It means that F is a function returning a pointer to a function with return type void taking one int argument.
Aug 24, 2012 at 5:26pm
@Peter Thank You. then why does it have a "void" there?
Aug 24, 2012 at 10:13pm
The void is the return type of the function you return.
Topic archived. No new replies allowed.