Is is possible to keep function pointers in an std::vector? And call each function in an iterator loop ?
Asked
Active
Viewed 92 times
1
-
4Did you mean to ask if it's possible to keep function pointers *in* a vector? Because it doesn't make sense to have a function pointer *to* a vector as a vector is not a function. – Matti Virkkunen Oct 01 '14 at 03:39
-
1Yes. More details and examples here: http://stackoverflow.com/questions/23488326/c-stdvector-of-references – alpartis Oct 01 '14 at 03:44
-
@MattiVirkkunen Technically I would like to know we can do that ? – Denny Oct 01 '14 at 03:44
-
@alpartis I mean function pointer , not just normal pointer – Denny Oct 01 '14 at 03:45
-
1A function pointer works just like any other pointer what comes to storing in a vector. – Matti Virkkunen Oct 01 '14 at 03:47
-
1A pointer is a pointer. It makes no difference whether pointing to a function or data, they are both just an address in memory. – alpartis Oct 01 '14 at 03:51
-
1@alpartis: Actually the C++ spec does make a reservation for platforms where data and function pointers aren't the same, and it's undefined behavior to cast a function pointer to a non-function pointer. On most modern platforms it's safe to do, but spec-wise, it's undefined. And in this case though, since we're not casting anything, it's not a problem. – Matti Virkkunen Oct 01 '14 at 03:58
2 Answers
3
Is it possible to keep function pointers in an
std::vector
?
Sure, as long as they are all of the same type:
void foo()
{
std::cout << "inside foo\n";
}
void bar()
{
std::cout << "inside bar\n";
}
void baz()
{
std::cout << "inside baz\n";
}
std::vector<void(*)()> fps { foo, bar, baz };
And call each function in an iterator loop?
No problem at all:
for (auto&& fp : fps)
{
fp();
}

fredoverflow
- 256,549
- 94
- 388
- 662
1
You might also want to consider the Boost Signals2 library. You can register any number of function pointers (AKA 'slots') to a 'signal' and have each one of them called by simply calling the 'signal' itself. The library takes care of managing the list of function pointers and iterating through each of them as necessary.

alpartis
- 1,086
- 14
- 29