C++實現回調函數

#include <iostream>
#include <string>
#include <map>
#include <string.h>
using namespace std;

class Test
{
public:
    Test()
    {
        m_map.insert(std::pair<string, Call>("add", (Call)&Test::add));
        m_map.insert(std::pair<string, Call>("sub", (Call)&Test::sub));
        m_map.insert(std::pair<string, Call>("mul", (Call)&Test::mul));
    }

    void print(string method, int a, int b)
    {
        Mapit it = m_map.find(method);
        if (it == m_map.end())
        {
            cout << "no find function: " << method << endl;
        }
        else
        {
            (this->*m_map[method])(a, b);
        }
    }

public:
    ///Call是函數指針,有2個int類型的形參和void的返回值
    typedef void (Test::*Call)(int a, int b);

    ///CallMap是map<string, Call>這種數據類型的別名
    ///用CallMap定義了一個成員變量m_map
    typedef map<string, Call> CallMap;
    CallMap m_map;

    ///MapIt是CallMap::iterator這種迭代器的別名
    typedef CallMap::iterator Mapit;

    ///可以將add,sub和mul這三個函數放到m_map中
    void add(int a, int b)
    {
        cout << "a + b = " << a + b << endl;
    }
    void sub(int a, int b)
    {
        cout << "a - b = " << a - b << endl; 
    }

    void mul(int a, int b)
    {
        cout << "a * b = " << a * b << endl;
    }
};

int main()
{
    Test test;
    ///根據字符串找到想對應的函數進行操作
    test.print("add", 2, 1);
    test.print("sub", 2, 1);
    test.print("mul", 2, 2);
    test.print("div", 2, 2);

    return 0;
}
 

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