在C++11中我们如果要写一个通过tuple实现函数调用的函数要这样写:

    template<int...>
    struct IndexTuple{};

    template<int N, int... Indexes>
    struct MakeIndexes : MakeIndexes<N - 1, N - 1, Indexes...>    {};

    template<int... indexes>
    struct MakeIndexes<0, indexes...>
    {
        typedef IndexTuple<indexes...> type;
    };

    template<typename F, int ... Indexes, typename ... Args>
    static void call_helper(F f, IndexTuple<Indexes...>, const std::tuple<Args...>& tup)
    {
        f(std::get<Indexes>(tup)...);
    }

    template<typename F, typename ... Args>
    static void call(F f, const std::tuple<Args...>& tp)
    {
        call_helper(f, typename MakeIndexes<sizeof... (Args)>::type(), tp);
    }

在C++14中MakeIndexes和IndexTuple已经由utility库提供了,我们可以写得更简洁了,两个函数就可以了。

    template<typename F, size_t... I, typename ... Args>
    static void call_helper(F f, std::index_sequence<I...>, const std::tuple<Args...>& tup)
    {
        f(std::get<I>(tup)...);
    }

    template<typename F, typename ... Args>
    static void call(F f, const std::tuple<Args...>& tp)
    {
        call_helper(f, std::make_index_sequence<sizeof... (Args)>(), tp);
    }

这样写更省心啦o(∩_∩)o 。

相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-11
猜你喜欢
  • 2022-12-23
  • 2021-12-31
  • 2022-12-23
  • 2021-12-01
  • 2021-12-21
  • 2021-12-15
  • 2021-11-28
相关资源
相似解决方案