toctave

t(iny)octave
git clone https://0xff.ir/g/toctave.git
Log | Files | Refs | README

scope.hpp (2256B)


      1 /*
      2     Copyright 2015 Adobe
      3     Distributed under the Boost Software License, Version 1.0.
      4     (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
      5 */
      6 
      7 /**************************************************************************************************/
      8 
      9 #ifndef STLAB_SCOPE_HPP
     10 #define STLAB_SCOPE_HPP
     11 
     12 /**************************************************************************************************/
     13 
     14 #include <mutex>
     15 #include <tuple>
     16 #include <utility>
     17 
     18 /**************************************************************************************************/
     19 
     20 namespace stlab {
     21 
     22 /**************************************************************************************************/
     23 
     24 inline namespace v1 {
     25 /**************************************************************************************************/
     26 
     27 namespace detail {
     28 
     29 template <typename T, typename Tuple, size_t... S>
     30 auto scope_call(Tuple&& t, std::index_sequence<S...>) {
     31     T scoped(std::forward<std::tuple_element_t<S, Tuple>>(std::get<S>(t))...);
     32     (void)scoped;
     33 
     34     // call the function
     35     constexpr size_t last_index = std::tuple_size<Tuple>::value - 1;
     36     return std::forward<std::tuple_element_t<last_index, Tuple>>(std::get<last_index>(t))();
     37 }
     38 
     39 } // namespace detail
     40 
     41 /**************************************************************************************************/
     42 
     43 template <typename T, typename... Args>
     44 inline auto scope(Args&&... args) {
     45     return detail::scope_call<T>(std::forward_as_tuple(std::forward<Args>(args)...),
     46                                  std::make_index_sequence<sizeof...(args) - 1>());
     47 }
     48 
     49 /* Workaround until VS2017 bug is fixed */
     50 template <typename T, typename F>
     51 inline auto scope(std::mutex& m, F&& f) {
     52     T scoped(m);
     53     return std::forward<F>(f)();
     54 }
     55 
     56 /**************************************************************************************************/
     57 
     58 } // namespace v1
     59 
     60 /**************************************************************************************************/
     61 
     62 } // namespace stlab
     63 
     64 /**************************************************************************************************/
     65 
     66 #endif
     67 
     68 /**************************************************************************************************/