std::tuple作為參數invoke調用函數


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轉換成序列。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM