2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * Defines a function folly::applyTuple, which takes a function and a
19 * std::tuple of arguments and calls the function with those
24 * int x = folly::applyTuple(std::plus<int>(), std::make_tuple(12, 12));
35 //////////////////////////////////////////////////////////////////////
38 namespace apply_tuple {
40 template <std::size_t...>
41 struct IndexSequence {};
43 template <std::size_t N, std::size_t... Is>
44 struct MakeIndexSequence : MakeIndexSequence<N - 1, N - 1, Is...> {};
46 template <std::size_t... Is>
47 struct MakeIndexSequence<0, Is...> : IndexSequence<Is...> {};
49 template <class Tuple>
50 using MakeIndexSequenceFromTuple =
51 MakeIndexSequence<std::tuple_size<typename std::decay<Tuple>::type>::value>;
53 // This is to allow using this with pointers to member functions,
54 // where the first argument in the tuple will be the this pointer.
56 inline constexpr F&& makeCallable(F&& f) {
57 return std::forward<F>(f);
59 template <class M, class C>
60 inline constexpr auto makeCallable(M(C::*d)) -> decltype(std::mem_fn(d)) {
61 return std::mem_fn(d);
64 template <class F, class Tuple, std::size_t... Indexes>
65 inline constexpr auto call(F&& f, Tuple&& t, IndexSequence<Indexes...>)
67 std::forward<F>(f)(std::get<Indexes>(std::forward<Tuple>(t))...)) {
68 return std::forward<F>(f)(std::get<Indexes>(std::forward<Tuple>(t))...);
71 } // namespace apply_tuple
74 //////////////////////////////////////////////////////////////////////
76 template <class F, class Tuple>
77 inline constexpr auto applyTuple(F&& f, Tuple&& t)
78 -> decltype(detail::apply_tuple::call(
79 detail::apply_tuple::makeCallable(std::forward<F>(f)),
80 std::forward<Tuple>(t),
81 detail::apply_tuple::MakeIndexSequenceFromTuple<Tuple>{})) {
82 return detail::apply_tuple::call(
83 detail::apply_tuple::makeCallable(std::forward<F>(f)),
84 std::forward<Tuple>(t),
85 detail::apply_tuple::MakeIndexSequenceFromTuple<Tuple>{});
88 //////////////////////////////////////////////////////////////////////