Your Ad Here
首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > 泛化的ScopeGuard模板类
【标  题】:泛化的ScopeGuard模板类
【关键字】:ScopeGuard
【来  源】:http://blog.csdn.net/SolidusSnake/archive/2006/09/08/1197033.aspx

泛化的ScopeGuard模板类

Your Ad Here

 

#pragma once

#include 
<cassert>
#include 
<memory>
#include 
"non_copy_able.h"



class ScopeGuardImp : private NonCopyable
{
public:
        ScopeGuardImp() 
{ };
        
virtual ~ScopeGuardImp(){ }
}
;



template
<class Type, class Fore, class Aft>                    
class ScopeGuardMF : public ScopeGuardImp

private:
        typedef typename 
void (Type::*MFun)(void);
private:
        Type    
*m_type;
        Fore    m_fore;
        Aft        m_aft;
public:
        ScopeGuardMF(Type 
*ptype, Fore fore, Aft aft)
        
{
                assert(ptype 
!= NULL);
                m_type 
= ptype;
                m_fore 
= fore;
                m_aft 
= aft;
                (m_type
->*m_fore)();
        }


        
~ScopeGuardMF()
        
{
                (m_type
->*m_aft)();
        }

}
;


template
<class Fore, class Aft>
class ScopeGuardFun : public ScopeGuardImp

private:
        Fore    m_fore;
        Aft        m_aft;
public:
        ScopeGuardFun(Fore fore, Aft aft)
        
{
                m_fore 
= fore;
                m_aft 
= aft;
                m_fore();
        }

        
        
~ScopeGuardFun()
        
{
                m_aft();
        }


}
;


class ScopeGuard  : private NonCopyable
{
private:
        std::auto_ptr
<ScopeGuardImp>   m_pimp;
public:
        template
<typename Type, typename Fore, typename Aft>
        ScopeGuard(Type 
*ptype, Fore fore, Aft aft)
        
{
                m_pimp.reset(
new ScopeGuardMF<Type, Fore, Aft>(ptype, fore, aft));
        }

        
        template
<typename Fore, typename Aft>
        ScopeGuard(Fore fore, Aft aft)
        
{
                m_pimp.reset(
new ScopeGuardFun<Fore, Aft>(fore, aft));
        }


        
~ScopeGuard() { }

}
;



 

测试代码:

 



class Test
{
public:
        
int fore() { printf("fore ");  return 8;}
        
void after() { printf("after "); }
}
;

void fore() { printf("aaaaa "); }
double after() { printf("bbbbb "); return 33.6;}

int main()
{
        
{
                Test test;
                ScopeGuard guard1(
&test, &Test::fore, &Test::after);
        }

        
{
                ScopeGuard guard2(fore, after);
        }

        
        
        cin.
get();

        
return 0;
}
;
C++的流basic_streambuf:【上一篇】
c programe language learn notes 1:【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • 光驱为何不读盘?
  • Openlaszlo实现简单的标签菜单
  • ODBC 获得结果
  • KooMail 2.62 正式版发布
  • Solaris 域名系统配置
  • 处理弹出窗口及广告文件
  • pb函数库之数据类型检查与转换函数
  • Linux 内核中的 Device Mapper 机制
  • COM对象创建过程总结(进程外和进程内)
  • 用JXL写EXCEL方法的封装[原]
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 bbb软讯网络 All Rigths Reserved.