tuple_util.hpp 1.68 KB
Newer Older
Matthieu Dorier's avatar
Matthieu Dorier committed
1 2 3 4 5
/*
 * (C) 2017 The University of Chicago
 * 
 * See COPYRIGHT in top-level directory.
 */
6 7 8 9 10 11 12 13 14 15 16 17
#ifndef __THALLIUM_TUPLE_UTIL_HPP
#define __THALLIUM_TUPLE_UTIL_HPP

#include <tuple>

namespace thallium {

namespace detail {

template<size_t N>
struct apply_f_to_t_impl {

18
    template<typename R, typename... ArgsF, typename... ArgsT, typename... Args>
19 20
    static R apply(const std::function<R(ArgsF...)>& f, std::tuple<ArgsT...>& t, Args&&... args) {
        return apply_f_to_t_impl<N-1>::apply(f, t, std::get<N-1>(t), std::forward<Args>(args)...);
21
    }
22 23 24 25 26
};

template<>
struct apply_f_to_t_impl<0> {

27
    template<typename R, typename... ArgsF, typename... ArgsT, typename... Args>
28 29
    static R apply(const std::function<R(ArgsF...)>& f, std::tuple<ArgsT...>& t, Args&&... args) {
        return f(std::forward<Args>(args)...);
30
    }
31 32 33 34 35 36 37 38 39 40 41 42
};

}

/**
 * Applies a function with arbitrary arguments to a tuple holding the same types of arguments.
 *
 * \param f : function to call on the tuple.
 * \param t : tupe of arguments.
 * \return the value returned by f.
 */
template<typename R, typename... ArgsF, typename... ArgsT>
43
R apply_function_to_tuple(const std::function<R(ArgsF...)>& f, std::tuple<ArgsT...>& t) {
44
    return detail::apply_f_to_t_impl<sizeof...(ArgsT)>::apply(f,t);
45 46 47 48 49 50 51 52 53 54
}

/**
 * Applies a function with arbitrary arguments to a tuple holding the same types of arguments.
 *
 * \param f : function to call on the tuple.
 * \param t : tupe of arguments.
 * \return the value returned by f.
 */
template<typename R, typename... ArgsF, typename... ArgsT>
55
R apply_function_to_tuple(R (*f)(ArgsF...), std::tuple<ArgsT...>& t) {
56 57
    std::function<R(ArgsF...)> fun(f);
    return apply_function_to_tuple(fun,t);
58 59 60 61 62
}

}

#endif