C++把函數指針存入map中

將函數指針轉換爲int,保存到map中,再根據字符串調用:

#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
//用來保存函數指針的map
map<string, int> mFuncPtr;
//定義一個函數
void* function1()
{
    printf("I am function1.\n");
    return NULL;
}
void* function2()
{
    printf("I am function2.\n");
    return NULL;
}
//將函數指針保存到map中
void saveFunction()
{
    //cout << (int)&function << endl;
    mFuncPtr.insert( make_pair<string, int>("fun1", (int)&function1) );
    mFuncPtr.insert( make_pair<string, int>("fun2", (int)&function2) );
}
//根據名字獲取函數
int getFunction(string funcName )
{
    map<string, int>::iterator it = mFuncPtr.find(funcName);
    if(it != mFuncPtr.end() )
        return it->second;
    return 0;
}
int main(int argc, char *argv[])
{
    saveFunction();
    //聲明類型
    typedef void* (*FUNC)();
    //獲取函數
    int fptr = getFunction("fun1");
    //cout << fptr << endl;
    if( fptr != 0 )
    {
        //調用函數fun1
        ((FUNC)fptr)();
    }
    //獲取函數
    fptr = getFunction("fun2");
    //cout << fptr << endl;
    if( fptr != 0 )
    {
        //調用函數fun2
        ((FUNC)fptr)();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章