Save Function Pointers in Arrays C++

I need to save in Arrays method pointers, something like this:

int main() {
void* man[10];
man[0]= void* hello();
man[0](2);


}

void hello(int val){

}

The question is, i can do that?

Thanks

Upvotes: 1

Views: 1607

Answers (2)

user4581301
user4581301

Reputation: 33931

Yes you can, but may I recommend std::function? It handles more complex cases, such as pointers to class methods, much more easily.

Here's an example of both the function pointer way and the std::function way:

#include <iostream>
#include <functional> // for std::function

//typedef void (*funcp)(int); // define a type. This makes everything else way, way easier.
//The above is obsolete syntax.
using funcp = void(*)(int); // Welcome to 2011, monkeyboy. You're five years late


void hello(int val) // put the function up ahead of the usage so main can see it.
{
    std::cout << val << std::endl;
}


int main()
{
    funcp man[10]; 
    man[0]= hello;
    man[0](2);

    std::function<void(int)> man2[10]; // no need for typdef. Template takes care of it
    man2[0] = hello;
    man2[0](3);

}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477010

Yes, you can easily achieve this by creating an array of function pointers. This is most readable if you alias the function type first:

void hello(int);
void world(int);

int main()
{
    using fn = void(int);
    fn * arr[] = { hello, world };
}

Usage:

fn[0](10);
fn[1](20);

Without a separate alias the syntax is a little hairer:

void (*arr[])(int) = { hello, world };

Or:

void (*arr[2])(int);
arr[0] = hello;
arr[1] = world;

Upvotes: 3

Related Questions