运用函数指针和STL的Map实现关键字key与成员函数的映射
2017-03-22 23:36
411 查看
今天的做自动化测试框架的时候发现需要向一个exe传入参数,实现对不同函数的调用,参数是函数名funName,还可以传入
执行函数的次数num;这个时候传入之后会使用很多的判断执行相关的函数,很多时候我们都会遇到用if-else来进行大量判断的情况
根据funName来执行函数
听了公司前辈的定义,这个涉及到了函数指针和STL的Map的使用
例子可以如下:
#include "stdafx.h"
//#include "person.h"
#include <iostream>
#include "string"
#include "map"
using namespace std;
class test
{
public :
void fun1() { cout<<"call test::fun1"<<endl; }
void fun2() { cout<<"call test::fun2"<<endl; }
void fun3() { cout<<"call test::fun3"<<endl; }
test()
{
m_mapFun["test::fun1"] = &test::fun1;
m_mapFun["test::fun2"] = &test::fun2;
m_mapFun["test::fun3"] = &test::fun3;
}
void call(string strfun)
{
if (m_mapFun.find(strfun) == m_mapFun.end())
cout<<"no function : "<<strfun<<endl;
else
(this->*m_mapFun[strfun])();
}
protected :
typedef void (test::*mfun)();
map<string, mfun> m_mapFun;
};
int _tmain(int argc, _TCHAR* argv[])
{
//Person person1;
test t;
t.call("test::fun1");
t.call("test::fun2");
t.call("test::fun3");
t.call("test::fun4");
return 0;
}
运行结果如下:
函数的执行次数传入还在研究中,主要用于测试。
执行函数的次数num;这个时候传入之后会使用很多的判断执行相关的函数,很多时候我们都会遇到用if-else来进行大量判断的情况
根据funName来执行函数
听了公司前辈的定义,这个涉及到了函数指针和STL的Map的使用
例子可以如下:
#include "stdafx.h"
//#include "person.h"
#include <iostream>
#include "string"
#include "map"
using namespace std;
class test
{
public :
void fun1() { cout<<"call test::fun1"<<endl; }
void fun2() { cout<<"call test::fun2"<<endl; }
void fun3() { cout<<"call test::fun3"<<endl; }
test()
{
m_mapFun["test::fun1"] = &test::fun1;
m_mapFun["test::fun2"] = &test::fun2;
m_mapFun["test::fun3"] = &test::fun3;
}
void call(string strfun)
{
if (m_mapFun.find(strfun) == m_mapFun.end())
cout<<"no function : "<<strfun<<endl;
else
(this->*m_mapFun[strfun])();
}
protected :
typedef void (test::*mfun)();
map<string, mfun> m_mapFun;
};
int _tmain(int argc, _TCHAR* argv[])
{
//Person person1;
test t;
t.call("test::fun1");
t.call("test::fun2");
t.call("test::fun3");
t.call("test::fun4");
return 0;
}
运行结果如下:
函数的执行次数传入还在研究中,主要用于测试。
相关文章推荐
- 非静态成员函数做窗口过程(非映射表实现),成员函数做消息映射
- STL源码中map和set中key值不能修改的实现
- 定义自己的STL map key的类型和比较函数
- ORA-14400: 插入的分区关键字未映射到任何分区】/【ORA-14400: inserted partition key does not map to any partition
- 解析包的关键字 获得handler 映射到具体的实现函数 client_packet.cpp
- 使用unordered_map和函数指针实现类私有函数的调用
- HDU 4287 Intelligent IME(STL 映射map的运用)
- 使用成员函数管理map STL
- STL源码中map和set中key值不能修改的实现
- 指向类成员函数的函数指针及#define typedef 实现类成员函数的类型转换
- STL中map的成员函数insert的返回值
- STL中map的成员函数insert的返回值
- 使用C++STL的map容器实现一种命令映射
- stl::map类常用成员函数
- 解析包的关键字 获得handler 映射到具体的实现函数 client_packet.h
- 函数指针作为结构体成员,实现函数注册
- STL中map的成员函数insert的返回值
- C++STL(vector,map,set,list)成员函数整理
- 关于成员函数的Command模式的简单实现
- 函数指针调用类的成员函数