template<typename Function, typename Tuple, std::size_t... Index>
decltype(auto) invoke_impl(Function&& func, Tuple&& t, std::index_sequence<Index...>)
{
    return func(std::get<Index>(std::forward<Tuple>(t))...);
}

template<typename Function, typename Tuple>
decltype(auto) invoke(Function&& func, Tuple&& t)
{
    constexpr auto size = std::tuple_size<typename std::decay<Tuple>::type>::value;
    return invoke_impl(std::forward<Function>(func), std::forward<Tuple>(t), std::make_index_sequence<size>{});
}


使用:

int add(int a, int b)
{
    return a + b;
}

int main()
{
    std::tuple<int, int> t = std::make_tuple(1, 2);
    std::cout << invoke(add, t) << std::endl;
    return 0;
}

这里用到了C++14的std::index_sequence,std::index_sequence很有用,它可以将std::array和std::tuple转换成序列。

相关文章:

  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2021-11-08
  • 2021-11-28
  • 2021-09-20
猜你喜欢
  • 2022-12-23
  • 2021-07-21
  • 2021-11-21
  • 2022-12-23
  • 2022-02-27
  • 2022-12-23
  • 2021-11-27
相关资源
相似解决方案