有时候要根据参数以运行指定的函数,这里面的比较简单,这若干个函数的类型是相同的,最容易想到的办法是使用switch case或者if else等实现一个一个对比调用,代码往往很长,这里以函数指针的方式实现,代码比较简单了就。
exam.hpp 头文件
#ifndef EXAM_HPP
#define EXAM_HPP
#include <string>
#include <map>
class Exam;
typedef void (Exam::*FuncT)(Type1);
class Exam
{
public:
Exam();
void dispatch(std::string key, Type1 param);
......
void onFunc1(Type1);
void onFunc2(Type1);
void onFunc3(Type1);
void onFunc4(Type1);
private:
static std::map<std::string, FuncT> mapFunc;
};
#endif
exam.cpp
#include "exam.hpp"
std::map<std::string, FuncT> Exam::mapFunc;
Exam::Exam()
{
if (mapFunc.empty())
{
mapFunc["one"] = &Exam::onFunc1;
mapFunc["two"] = &Exam::onFunc2;
mapFunc["three"] = &Exam::onFunc3;
mapFunc["four"] = &Exam::onFunc4;
}
}
void Exam::dispatch(std::string key, Type1 param)
{
if (mapFunc.find(key) != mapFunc.end())
{
(this->*mapFunc[key])(param);
}
}
void Exam::onFunc1(Type1 param)
{
}
void Exam::onFunc2(Type1 param)
{
}
void Exam::onFunc3(Type1 param)
{
}
void Exam::onFunc4(Type1 param)
{
}
通过以上方法,实现了根据键自动分配要处理的函数的问题。维护起来比较简单。