【问题标题】:Get the subset of a parameter pack based on a given set of indices根据给定的一组索引获取参数包的子集
【发布时间】:2013-11-03 22:25:56
【问题描述】:

好吧,这真的很难。

我希望能够通过在给定的一组有效索引处选择参数类型来获取参数包的子集,然后将该参数包用作函数的参数列表。即:

template <size_t... indices_t>
void func(pack_subset<indices_t..., args_t...>); //incorrect syntax,
                                                 //not sure how else to write this
                                                 //args_t is predetermined, this
                                                 //function is a static member of
                                                 //a variadic class template

//For a parameter pack <float, double> and index set 0
void func(float); // <- result of template

我可以获取单个索引的类型,但是一组索引有点困难,尤其是当该组的大小可变时。其语法是:

pack_index<size_t index_t, typename... args>::type

也许我可以将一堆这些串在一起,但我不确定如何扩展 indices_t 以便为列表中的每个值获取一个 pack_index。

【问题讨论】:

    标签: c++ templates parameters variadic-templates template-meta-programming


    【解决方案1】:

    如果你将参数包装成一个元组,那就很简单了:

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

    示例输入:&lt;int, double, float, char, bool&gt;, 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;
    }
    

    输出:

    std::tuple<double, char>
    

    您需要做的就是使用std::tuple&lt;args_t...&gt;,此时您只有args_t...


    这里有一个替代想法,可以将这个想法构建成更容易处理的东西:

    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)
        {
            // ...
        }
    };
    

    用法:

    selector<int, char, bool, double>::call<0, 2>(1, true);   // int, bool
    

    【讨论】:

    • 啊,你能解释一下这个上下文中的 using 关键字吗?我从没见过这样用的。
    • @NmdMystery:这和typedef std::tuple&lt;...&gt; type; 是一样的。 C++11 中的新功能。
    • 我在实现这一点时遇到了一些麻烦,尽管结构模板可以编译。这就是我所拥有的:template&lt;size_t... indices_t&gt; void func(selector&lt;std::tuple&lt;args_t...&gt;, indices_t...&gt;) 这也可以编译,我只是不确定如何提供参数,因为代码完成在 Visual Studio 中并没有真正帮助我
    • @NmdMystery:您可能应该将静态函数包装到类模板中,并将其部分专门用于元组,并制作一个单独的辅助函数来调用静态类模板函数。
    • @NmdMystery:我添加了一个使用静态类模板成员模板的替代实现。
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2013-01-02
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多