简体   繁体   中英

Storing a function pointer in a map as a value

I am trying to store a function pointer in a map as value with the below code. I am working on solaris sparc server. Below is the code that i have written.

#include<iostream>
#include<sstream>
#include<map>

using namespace std;

typedef int (*spl_handler)(int,string,char *);
typedef map<string, spl_handler> mo_map;

int foo(int,char,char *);
int bar(int,char,char *);

int foo(int a,string b,char * str)
{
cout <<"i am in foo "<<a<<endl;
cout <<"i am in foo "<<b<<endl;
cout <<"i am in foo "<<str<<endl;
return 0;
}

int bar(int a,string b,char * str)
{
cout <<"i am in bar "<<a<<endl;
cout <<"i am in bar "<<b<<endl;
cout <<"i am in bar "<<str<<endl;
return 0;
}


int main()
{
mo_map m;
//m["foo"]=&foo; //compiling works if i write like this .
m.insert(std::pair<string,spl_handler>(string("foo"),&foo)); //compilation fails here????
return 0;
}

I am getting an error saying:

> CC spl_handler.cc
"spl_handler.cc", line 34: Error: Could not find a match for std::pair<std::string, int(*)(int,std::string,char*)>::pair(std::string, int(*)(int,char,char*)) needed in main().
1 Error(s) detected.

but assigning directly without an insert works.

Can anybody tell me why the compilation is failing here?

int foo(int,char,char *);
int bar(int,char,char *);

You are wrong in second parameter, it should be string . Also, it's better to use std::make_pair , instead of construct pair manually.

Could be your forward declarations that are throwing off the compiler. These don't match the actual function definitions, and aren't needed in this example anyway:

int foo(int,char,char *);
int bar(int,char,char *);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM