C++中table_driven实现:降低圈复杂度

1、实现代码: ==关注头文件 ==

// table_map.h  
#ifndef TABLE_MAP_H 
#define TABLE_MAP_H 

#include <iostream>
#include <map>  
#include <utility>  
#include <initializer_list> 
#include <functional> 

using namespace std;  

template <class key, class func = std::function<void()>, class tb_map = std::map<key, func>>  
class table_driven
{ 
public:   
	using value_type = typename tb_map::value_type;   
	table_driven() = default;    
	~table_driven() = default;  

public:     
	// 使用初始化列表初始化   
	// 需要使用 typename 关键字,来使编译器区分嵌套类型与嵌套值 
	table_driven(std::initializer_list<value_type> il) : table_driven_map_(il) {}     
	// 以下两个构造函数与上面的一样   
	// table_driven(std::initializer_list<pair<key, func>> il) {}     
	// table_driven(std::initializer_list<typename tb_map::value_type> il) {}    

	void insert(const key& first_value, func&& second_value)     
	{         
		table_driven_map_[first_value] = std::move(second_value);   
	}  

public:  
	template <typename... Args>    
	bool handle_key(const key& first_value, Args... args)   
	{     
		auto iter = table_driven_map_.find(first_value);       
		if (iter != table_driven_map_.end()) {     
			iter->second(args...);       
			return true;      
		}          
		return false; 
	} 

private:    
	tb_map table_driven_map_; 
};  
#endif

// table_map.cpp 
#include <table_map.h>  

void func1() {cout << "func1" << endl;}  
void func2() {cout << "func2" << endl;}
void func3(int a, double b) {cout << "func3 " << a << b << endl;} 
void func4(int a, double b) {cout << "func4 " << a << b << endl;}   

int main()
{    
	int condition = 2;  // key值     
	int val1 = 3;     
	double val2 = 4;  
	  
	// 简单,推荐使用   
	table_driven<int> table1{   
		{1, func1},  // 使用默认func参数,调用无参函数       
		{2, [&]() {func3(val1,val2);}}  // 使用lambda表达式作为无参形式,实际调用有参函数  
	};  
	table1.handle_key(condition);     
	
	// 复杂,不推荐使用    
	table_driven<int, std::function<void(int, double)>> table2{    
		{1, func3},  // 主动修改模板func参数为有参函数       
		{2, func4}   
	};   
	table2.handle_key(condition, val1, val2);    
	return 0;
}  

参考资料:
1、C++的表驱动法
2、提高C++代码质量 - [111]用表驱动取代冗长的逻辑选择
3、模板与泛型编程知识点:编译期多态、typename标识嵌套从属类型名称

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值