vector of function pointers
Mar 7, 2010 at 6:39pm UTC
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.
Mar 7, 2010 at 6:46pm UTC
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 Mar 7, 2010 at 6:47pm UTC
Mar 7, 2010 at 6:51pm UTC
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 Mar 7, 2010 at 6:52pm UTC
Mar 7, 2010 at 6:54pm UTC
Ah alright, thanks.
But why does it use brackets to call the function? Just curious.
Mar 7, 2010 at 6:55pm UTC
But why does it use brackets to call the function?
What do you mean, where?
Mar 7, 2010 at 6:57pm UTC
Just weird to me that it wouldn't be v.at(0)(); or something...
Mar 7, 2010 at 6:58pm UTC
v.at(0) is the same as v[0] except at() does bounds checking and [] does not.
Mar 7, 2010 at 7:01pm UTC
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;
.
Mar 7, 2010 at 7:01pm UTC
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.