Get the subset of a parameter pack based on a given set of indices

做~自己de王妃 提交于 2019-12-06 12:06:07

If you wrap the arguments into a tuple, it's pretty straight-forward:

#include <tuple>

template <typename T, std::size_t ...Is>
struct selector
{
    using type = std::tuple<typename std::tuple_element<Is, T>::type...>;
};

Example input: <int, double, float, char, bool>, 1, 3

#include <iostream>
#include <demangle.hpp>

int main()
{
    std::cout
        << demangle<selector<std::tuple<int, double, float, char, bool>, 1, 3>::type>()
        << std::endl;
}

Output:

std::tuple<double, char>

All you need to do is use std::tuple<args_t...> where you have just args_t... at the moment.


Here's an alternative idea for structuring that idea into something easier to handle:

template <typename ...Args> struct selector
{
    using T = std::tuple<Args...>;

    template <std::size_t ...Is>
    static void call(typename std::tuple_element<Is, T>::type ...args)
    {
        // ...
    }
};

Usage:

selector<int, char, bool, double>::call<0, 2>(1, true);   // int, bool
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!