Imported Upstream version 14.45.0
[platform/upstream/libzypp.git] / zypp / base / DtorReset.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/base/DtorReset.h
10  *
11 */
12 #ifndef ZYPP_BASE_DTORRESET_H
13 #define ZYPP_BASE_DTORRESET_H
14
15 #include "zypp/base/PtrTypes.h"
16
17 ///////////////////////////////////////////////////////////////////
18 namespace zypp
19 { /////////////////////////////////////////////////////////////////
20
21   ///////////////////////////////////////////////////////////////////
22   //
23   //    CLASS NAME : DtorReset
24   //
25   /** Assign a vaiable a certain value when going out of scope.
26    * Use it e.g. to reset/cleanup in presence of exceptions.
27    * \code
28    * struct Foo
29    * {
30    *   void consume()
31    *   {
32    *     DtorReset x(_inConsume,false);
33    *     _inConsume = true;
34    *     MIL << _inConsume << endl;
35    *   };
36    *
37    *   DefaultIntegral<bool,false> _inConsume;
38    * };
39    *
40    * Foo f;
41    * MIL << f._inConsume << endl; // 0
42    * f.consume();                 // 1
43    * MIL << f._inConsume << endl; // 0
44    * \endcode
45    * \ingroup g_RAII
46    * \todo Check if using call_traits enables 'DtorReset(std::string,"value")',
47    * as this currently would require assignment of 'char[]'.
48    */
49   class DtorReset
50   {
51   public:
52     template<class _Var>
53       DtorReset( _Var & var_r )
54       : _pimpl( new Impl<_Var,_Var>( var_r, var_r ) )
55       {}
56     template<class _Var, class _Val>
57       DtorReset( _Var & var_r, const _Val & val_r )
58       : _pimpl( new Impl<_Var,_Val>( var_r, val_r ) )
59       {}
60
61   private:
62     /** Requires _Val being copy constructible, and assignment
63      * <tt>_Var = _Val</tt> defined. */
64     template<class _Var, class _Val>
65       struct Impl
66       {
67         Impl( _Var & var_r, const _Val & val_r )
68         : _var( var_r )
69         , _val( val_r )
70         {}
71         ~Impl()
72         { _var = _val; }
73         _Var & _var;
74         _Val   _val;
75       };
76     shared_ptr<void> _pimpl;
77   };
78   ///////////////////////////////////////////////////////////////////
79
80   /////////////////////////////////////////////////////////////////
81 } // namespace zypp
82 ///////////////////////////////////////////////////////////////////
83 #endif // ZYPP_BASE_DTORRESET_H