首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从参数包创建索引和类型对

从参数包创建索引和类型对
EN

Stack Overflow用户
提问于 2016-08-03 14:10:46
回答 1查看 628关注 0票数 2

我正在尝试创建一个或多对索引,一个参数包。

下面是代码希望实现的一个示例:

代码语言:javascript
复制
  {
    using Indices =
        std::tuple< IndexTypePair< 0, int >, IndexTypePair< 1, int >, IndexTypePair< 2, float > >;
    test2< Indices, 0 >();
    test2< Indices, 1 >();
    test2< Indices, 2 >();
  }

这里有一个概括:

代码语言:javascript
复制
  {
    template < typename... T >
    using make_index_tuple = tuple< IndexTypePair< Index_v< T, T... >, T >... >;
    using Indices = make_index_tuple< int, int, float >;
    test2< Indices, 0 >();
    test2< Indices, 1 >();
    test2< Indices, 2 >();
  }

这个解决方案是基于对这个问题的回答:如何在可变类型包中获取类型的索引?

我遇到的问题之一是创建可变模板别名,前面的代码给出了以下错误:

代码语言:javascript
复制
$ make index-sequence clang++-3.8 -Wall -Werror -Wextra -std=c++14
-pedantic -Wconversion -stdlib=libc++ -O3 -pthread    index-sequence.cpp   -o index-sequence index-sequence.cpp:50:5: error: expected expression
    template < typename... T >
    ^ index-sequence.cpp:52:21: error: unknown type name 'make_index_tuple'
    using Indices = make_index_tuple< int, int, float >;
                    ^ ...

下面是使代码工作的其他一些部分:

代码语言:javascript
复制
#include <array>
#include <cstddef>
#include <iostream>
#include <type_traits>
#include <utility>

template < typename T, typename... Ts >
struct Index;

template < typename T, typename... Ts >
struct Index< T, T, Ts... > : std::integral_constant< std::size_t, 0 >
{
};

template < typename T, typename U, typename... Ts >
struct Index< T, U, Ts... > : std::integral_constant< std::size_t, 1 + Index< T, Ts... >::value >
{
};

template < typename T, typename... Ts >
constexpr std::size_t Index_v = Index< T, Ts... >::value;

template < size_t i, typename T >
struct IndexTypePair
{
  static constexpr size_t index{i};
  using Type = T;
};

template < typename Idx, size_t i >
void test2()
{
  using ITP = typename std::tuple_element< i, Idx >::type;
  typename ITP::Type v{};
  //....
  std::cout << ITP::index << ' ' << v << std::endl;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-03 14:40:53

使用嵌套结构设置来帮助您,以及标准的make_index_sequence

代码语言:javascript
复制
template < typename ... T >
struct make_index_type_tuple_helper
{    
    template< typename V >
    struct idx;

    template< size_t ... Indices >
    struct idx<std::index_sequence<Indices...>>
    {
        using tuple_type = std::tuple<IndexTypePair<Indices, T>...>;
    };

    using tuple_type = typename idx<std::make_index_sequence<sizeof...(T)>>::tuple_type;
};

template < typename ... T>
using make_index_type_tuple = typename make_index_type_tuple_helper<T...>::tuple_type;

然后,您可以按照自己的意愿使用它(现场演示):

代码语言:javascript
复制
using Indices = make_index_type_tuple< int, int, float >;
test2< Indices, 0 >();
test2< Indices, 1 >();
test2< Indices, 2 >();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38746040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档