Calling Functions

This is going to sound redundant until you realize what I'm doing, but I want to send a function name through an argument to another function, and use that one to call the first.

The reason why is because I'm trying to build a function to mimic the JavaScript setInterval() (http://www.w3schools.com/HTMLDOM/met_win_setinterval.asp ) function, which allows you to have a function launch every so many milliseconds until the setInterval is cancelled with another function (see clearInterval (http://www.w3schools.com/HTMLDOM/met_win_clearinterval.asp )).

Is this possible?
Last edited on
You need to pass a pointer to the function you want to call.
Suppose you have function f(), and you want it to call a function that takes two ints and returns an int. You'd do it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int f(int (*functionPointer)(int,int),int a,int b){
	//     v   Parentheses  v not redundant!
	return (*functionPointer)(a,b);
}

//To call f():

int someFunction(int a,int b){
	return a+b;
}

int main(){
	std::cout <<f(&someFunction,1,2)<<std::endl;
	return 0;
}
Last edited on
Or like the STL algorithms, accept a function object.
Last edited on
Helios:

Your solution looks good. I haven't messed with pointers before, to be honest. Didn't know they existed (I'm not very advanced at programming at all). But now that I do, that gives me something to learn.

Seymore:

I'm going to take a look into what you mentioned as well. Even if I don't use it, I'll at least have the knowledge in my back pocket just in case I do need it.

Thank you both.
Also look at boost::function and boost::bind, which are more flexible than function pointers and function objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <boost/function.hpp>
#include <boost/bind.hpp>

typedef boost::function<int(int, int)> Callback;

int f( const Callback& cb, int a, int b ) {
    return cb( a, b );
}

int someFunction( int a, int b ) {
    return a + b;
}

int main() {
    std::cout << f( boost::bind( someFunction, 1, 2 ) ) << std::endl;
    return 0;
}
Topic archived. No new replies allowed.