通用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;

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");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值