Containers containing pointers to functions

B

Boris Glawe

Hi,

How can I declare the type of pointer to a function ??

I want to create a map (from STL), which contains pointers to functions
as values, but I have to declare the type:

void print_red(){
cout << "red" << endl;
}

void print_green(){
cout << "green" << endl;
}

void print_blue(){
cout << "blue" << endl;
}

map <string, "pointer to a function"> m;

m["red"] = print_red;
m["green"] = print_green;
m["blue"] = print_blue;

How can I specify the type of this function. The same problem exists
when you want to declare a function, which take a pointer to another
function as an argument.
How can this be done??

Thanks Boris
 
E

Erik

Hi,
How can I declare the type of pointer to a function ??

I want to create a map (from STL), which contains pointers to functions
as values, but I have to declare the type:

void print_red(){
cout << "red" << endl;
}

void print_green(){
cout << "green" << endl;
}

void print_blue(){
cout << "blue" << endl;
}

map <string, "pointer to a function"> m;

m["red"] = print_red;
m["green"] = print_green;
m["blue"] = print_blue;

#include <map>
#include <string>
#include <iostream>

using namespace std;

void print_red(){
cout << "red" << endl;
}

void print_green(){
cout << "green" << endl;
}

void print_blue(){
cout << "blue" << endl;
}

map<string, void (*)()> functions;

int main() {
functions["red"] = print_red;
functions["green"] = print_green;
functions["blue"] = print_blue;

functions["red"]();
}

/ Erik
 
B

Boris Glawe

Ok,

Thanks to all your answers ! It works fine, with one exception:

specifying the return type of funtions, which return pointers to functions.

is the following code correct (my compiler gives me a parse error)?

int func(){
return 5;
}

int (*)() func2(){ // here is the parse error !!
return &func;
}

int main(){
int (*)() ptr = func2();
cout << ptr() << endl;
}


It works fine, when I use typedef but not the way I did above.

greets Boris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top