#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;} ;