Vector of function pointers

This is just a small tip on how to define a vector of function pointers in C++ and how to call functions stored in it:

#include <vector>
#include <iostream>

typedef int (*fptr)(int, int);
int foo(int a, int b) { return a + b; }
int bar(int a, int b) { return a * b; }

int main()
{
    std::vector<fptr> f;
    f.push_back(foo);
    f.push_back(bar);

    std::cout << f[0](2, 3)
        << f[1](2, 3)
        << std::endl;
    return 0;
} 

That’s it. Next, this example could be extend to replace old-fashion function pointers with function objects.

Advertisements

3 thoughts on “Vector of function pointers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s