vector of function pointers

closed account (Sy0XoG1T)
I'm trying to do something like this...

1
2
3
4
5
6
7
8
9
10
11
void testfunc()
{
	cout << "hello" << endl;
}
int main()
{
	vector<void*> testvec;
	testvec.push_back(&testfunc);

	return 0;
}


This code gives me no errors so I think it's right so far but I'm not too sure on how to call the function or how to point to a function that takes arguments.
Never ever mix pointers (void pointers as well) with function pointers.
What you want to do should look something like this :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>

using namespace std;

void testfunc() {
    cout << "hello" << endl;
}

int main () {
    vector<void (*)()> v;
    v.push_back(&testfunc);
    v[0]();
}


Syntax is a bit complicated, to make it more simple use a typedef :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

using namespace std;

typedef void (*fp_t)();

void testfunc() {
    cout << "hello" << endl;
}

int main () {
    vector<fp_t> v;
    v.push_back(&testfunc);
    v[0]();
}
Last edited on
void* is a generic pointer that can point to anything.

This is not the same as a pointer to a function which returns void. But since a void* can point to anything, it can point to a function also.

This is easier to do with a typedef:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef void (*funcptr_t)();

void testfunc()
{
  cout << "hello" << endl;
}

int main()
{
  vector< funcptr_t > testvec;
  testvec.push_back( &testfunc );

  // to call the function:
  (*testvec[0])();
}


If you don't want to use the typedef, you can do this instead:

 
vector< void (*)() > testvec;


but note that's quite a bit uglier.


EDIT: doh, too slow
Last edited on
closed account (Sy0XoG1T)
Ah alright, thanks.

But why does it use brackets to call the function? Just curious.
But why does it use brackets to call the function?
What do you mean, where?
closed account (Sy0XoG1T)
 
v[0]();


Just weird to me that it wouldn't be v.at(0)(); or something...
v.at(0) is the same as v[0] except at() does bounds checking and [] does not.
v[0](); and v.at(0)(); does the same thing (except for the range check).
Why you need the (), is because if you only write v[0]; then you didn't yet called the function. It's like writing testfunc;.
closed account (Sy0XoG1T)
Ah alright. It wasn't working before with .at but now it is. :)

Thank you both for the help.
Topic archived. No new replies allowed.