Advertisement
Drainedsoul

C++ Unreadable Template Example

May 1st, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. /**
  2.  *  Attempts to perform an operation while holding
  3.  *  the lock, but only if the lock may be acquired
  4.  *  without blocking.
  5.  *
  6.  *  \tparam T
  7.  *      The type of the functor that is
  8.  *      to be executed while the lock is
  9.  *      held.
  10.  *  \tparam Args
  11.  *      The types of a parameter pack to be
  12.  *      forwarded to operator () of the
  13.  *      instance of \em T supplied.
  14.  *
  15.  *  \param [in] exec
  16.  *      The functor to execute while the
  17.  *      lock is held.
  18.  *  \param [in] args
  19.  *      A parameter pack whose types are
  20.  *      given by \em Args which shall be
  21.  *      forwarded to operator () of
  22.  *      \em exec.
  23.  *  \param [out] result
  24.  *      A pointer to an object of the type
  25.  *      returned by operator () of
  26.  *      \em exec.  This address location
  27.  *      will be populated with the value
  28.  *      returned by \em exec with arguments
  29.  *      \em args.  May be \em nullptr if
  30.  *      the return value of \em exec is
  31.  *      not desired.
  32.  *
  33.  *  \return
  34.  *      \em true if the lock was acquired
  35.  *      and \em exec was called, \em false
  36.  *      otherwise.
  37.  */
  38. template <typename T, typename... Args>
  39. auto TryExecute (
  40.     const T & exec,
  41.     Args &&... args,
  42.     decltype(exec(std::forward<Args>(args)...)) * result
  43. ) -> typename std::enable_if<
  44.     !std::is_same<
  45.         decltype(exec(std::forward<Args>(args)...)),
  46.         void
  47.     >::value,
  48.     bool
  49. >::type {
  50.  
  51.     if (!TryAcquire()) return false;
  52.  
  53.     try {
  54.    
  55.         if (result==nullptr) exec(std::forward<Args>(args)...);
  56.         else *result=exec(std::forward<Args>(args)...);
  57.    
  58.     } catch (...) {
  59.    
  60.         Release();
  61.        
  62.         throw;
  63.    
  64.     }
  65.    
  66.     Release();
  67.    
  68.     return true;
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement