使用boost的函数库实现通用switch-case/if.else选择器,该怎么处理
使用boost的函数库实现通用switch-case/if..else选择器
在通信行业做事久了,经常发现在写的程序中,大量重复出现if..else..这种嵌套层次相当深的switch写法,所以就蒙生了自己写一个通用switcher的想法,把这种强耦合的写法隔离,所以就用了下面的实现
/*********************************************
* 通用选择器
* 1. 适配原始函数指针
* 2. 适配成员函数指针
* 3. 适配仿函数
* 4. 绑定函数
********************************************/
template <typename RESULT,
typename KEY,
typename PARA>
class switcher
{
private:
typedef boost::function <RESULT, PARA> FUNCTOR;
public:
void add_observer(KEY key, FUNCTOR func)
{
functorset.insert(make_pair(key, func));
}
RESULT match(KEY key, PARA para)
{
map <KEY, FUNCTOR> ::const_iterator iter;
iter = functorset.find(key);
if (iter != functorset.end())
{
static_cast <FUNCTOR> (iter-> second)(para);
}
}
private:
map <KEY, FUNCTOR> functorset;
};
bool some_function(const std::string& s)
{
std::cout < < s < < " This is really neat\n ";
return true;
}
class some_class
{
public:
bool some_function(const std::string& s)
{
std::cout < < s < < " This is also quite nice\n ";
return true;
}
};
class some_function_object
{
public:
bool operator()(const std::string& s)
{
std::cout < < s < <
" This should work, too, in a flexible solution\n ";
return true;
}
};
switcher <bool, int, string> myswitcher;
在通信行业做事久了,经常发现在写的程序中,大量重复出现if..else..这种嵌套层次相当深的switch写法,所以就蒙生了自己写一个通用switcher的想法,把这种强耦合的写法隔离,所以就用了下面的实现
/*********************************************
* 通用选择器
* 1. 适配原始函数指针
* 2. 适配成员函数指针
* 3. 适配仿函数
* 4. 绑定函数
********************************************/
template <typename RESULT,
typename KEY,
typename PARA>
class switcher
{
private:
typedef boost::function <RESULT, PARA> FUNCTOR;
public:
void add_observer(KEY key, FUNCTOR func)
{
functorset.insert(make_pair(key, func));
}
RESULT match(KEY key, PARA para)
{
map <KEY, FUNCTOR> ::const_iterator iter;
iter = functorset.find(key);
if (iter != functorset.end())
{
static_cast <FUNCTOR> (iter-> second)(para);
}
}
private:
map <KEY, FUNCTOR> functorset;
};
bool some_function(const std::string& s)
{
std::cout < < s < < " This is really neat\n ";
return true;
}
class some_class
{
public:
bool some_function(const std::string& s)
{
std::cout < < s < < " This is also quite nice\n ";
return true;
}
};
class some_function_object
{
public:
bool operator()(const std::string& s)
{
std::cout < < s < <
" This should work, too, in a flexible solution\n ";
return true;
}
};
switcher <bool, int, string> myswitcher;