在通信行業做事久了,經常發現在寫的程序中,大量重複出現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");
}