How to extract a value from a variadic template parameter pack by index?

此生再无相见时 提交于 2019-12-05 12:49:23
template <size_t N, typename... Args>
decltype(auto) magic_get(Args&&... as) noexcept {
    return std::get<N>(std::forward_as_tuple(std::forward<Args>(as)...));
}

Change decltype(auto) to auto and add a trailing return type of decltype(/* the whole returned expression here */) if C++14 features are unavailable.


Tupleless version:

template <std::size_t N, typename Tfirst, typename... Args, std::enable_if_t<N == 0, int>...>
decltype(auto) magic_get(Tfirst&& first, Args&&... as) noexcept {
    return std::forward<Tfirst>(first);
}

template <std::size_t N, typename Tfirst, typename... Args, std::enable_if_t<N != 0, int>...>
decltype(auto) magic_get(Tfirst&& first, Args&&... as) noexcept {
    return magic_get<N - 1>(std::forward<Args>(as)...);
}

Note that this does not work in clang, thanks to clang bug 11723. Replacing std::enable_if_t<N != 0, int>... with std::enable_if_t<N != 0, int> = 0 is a simple workaround.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!