在通信行业做事久了,经常发现在写的程序中,大量重复出现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;
bool test(int number, string info)
{
return myswitcher.match(number, info);
}
int main(int argv, char** argc)
{
function1<bool,const std::string&> f1(&some_function);
function1<bool,const std::string&> f2(&some_class::some_function,&s);
function1<bool,const std::string&> f3(boost::bind(&some_class::some_function,&s,_1));
some_function_object fso;
function1<bool,const std::string&> f4(fso);
myswitcher.add_observer(0, f1);
myswitcher.add_observer(1, f2);
myswitcher.add_observer(2, f3);
myswitcher.add_observer(3, f4);
test(0, "call by f1");
}