c++ - 如何访问模板类型参数包中的类型索引?

标签 c++ c++11 templates

我想在将类型参数包扩展为 std::tuple<...> 时访问类型的索引.
例如,给定一个类型包 <int, double, float>我想建一个 std::tuple<...>看起来如下:

std::tuple<std::array<int,0>, std::array<double,1>, std::array<float, 2>>
//                     ^  ^                ^    ^                ^    ^
//                     T  I                T    I                T    I
这是一个几乎完全符合我想要的实现,但它仅适用于大小为 3 的类型包(请参阅 hack 旁边的注释)。如何解决此问题以独立于 TT... 工作尺码?
#include <tuple>
#include <utility>
#include <array>
#include <iostream>

template <typename... TT>
struct Foo {
    template <std::size_t... Indices>
    struct Baz {
       std::tuple<std::array<TT,Indices>...> baz;
    };
    Baz<0,1,2> bar; // <<<=== Here is the hack: I make a fixed-size pack; I want it to match TT...
};

int main() {
    Foo<int,double,float> foo;
    std::cout << std::get<0>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<1>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<2>(foo.bar.baz).size() << std::endl;
    return 0;
}
Live demo.

最佳答案

你在嵌套的正确轨道上有两个包。您现在需要的是一个 std::integer_sequence 这让您可以创建所需的包,而不是通过 Baz<0,1,2> bar; 对其进行硬编码.
基本思想是定义一个函数模板,它接受一个 std::integer_sequence<size_t,I...>在包上参数化并用 std::make_integer_sequence<size_t,N> 调用它所以包I...可以从一个数字N推导出来,那么它只是折叠:

#include <tuple>
#include <utility>
#include <array>
#include <iostream>
#include <utility>
#include <type_traits>

template <typename...Ts>
struct foo {
    static const size_t N = sizeof...(Ts);
    template <size_t ... I>
    static auto helper(std::integer_sequence<size_t,I...>){
        return std::tuple<std::array<Ts,I>...>{};
    }
    using type = decltype(helper(std::make_integer_sequence<size_t,N>{}));
};

int main() {
    std::cout << std::is_same< std::tuple<std::array<int,0>, std::array<double,1>, std::array<float, 2>>,
                 foo<int,double,float>::type >::value;
}
Live Demo

关于c++ - 如何访问模板类型参数包中的类型索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67306289/

相关文章:

c++ - OLE 入门 - 什么是好的学习项目选择?

c++ - 数组大小为 200 万的频繁数(适用于 500k 但挂起 200 万?)

c++ - C++14 及更高版本是否允许 Lambda 函数的默认参数?如果是这样怎么办?

c++ - 为什么以及如何在 C++ 中使用 bind() 作为谓词?

c++ - 将 C++ 模板类添加到列表

c++ - 在函数调用中使用模板模板参数

c++ - 为什么我的网络 TCP/UDP 实现不起作用?

c++ - 如何处理错误cygwin_exception::open_stackdumpfile

c++ - 何时使用 std::begin 和 std::end 而不是容器特定版本

c++ - 使用模板摆脱动态链接样板​​ : extern "C" and templates don't mix;