【问题标题】:How to automatically fill a std::array base on sizeof a variadic template?如何根据可变参数模板的 sizeof 自动填充 std::array?
【发布时间】:2014-06-10 17:57:08
【问题描述】:

在这个简化的代码中:

template <int... vars>
struct Compile_Time_Array_Indexes
{
    static std::array < int, sizeof...(vars)> indexes;//automatically fill it base on sizeof...(vars)
};
template <int ... vars>
struct Compile_Time_Array :public Compile_Time_Array_Indexes<vars...>
{
};

我想根据vars... 大小自动填充indexes

示例:

Compile_Time_Array <1,3,5,2> arr1;//indexes --> [0,1,2,3]
Compile_Time_Array <8,5> arr2;   // indexes --> [0,1]

有什么想法吗?

【问题讨论】:

  • C++14 带来了std::integer_sequence(虽然如果这些是索引,你可以考虑使用std::size_t,它有一个很好的预制std::index_sequence)。
  • 类似this Q&A? (也可以在没有 constexpr IIRC 的情况下使用)

标签: c++ templates c++11 variadic-templates c++14


【解决方案1】:

以下定义显然适用于 GCC-4.9 和 Clang-3.5:

template <typename Type, Type ...Indices>
auto make_index_array(std::integer_sequence<Type, Indices...>)
    -> std::array<Type, sizeof...(Indices)>
{
    return std::array<Type, sizeof...(Indices)>{Indices...};
}

template <int... vars>
std::array<int, sizeof...(vars)> 
Compile_Time_Array_Indexes<vars...>::indexes
    = make_index_array<int>(std::make_integer_sequence<int, sizeof...(vars)>{});

【讨论】:

  • 不过,这不会用索引填充数组。相反,它使用与参数包中相同的数字填充数组。
  • @chris:你是对的。我在OP的问题中没有看到这一点。我已经确定了答案。
  • @OP,您知道,对于 C++11 有许多这样的整数序列的实现,您可以抓住其中一个并将其与这段代码一起使用。
  • @nosid 我正在尝试在 vs 2013 中编译它我添加了 make_integer_sequence 的实现,但是这一行给了我一个错误Compile_Time_Array_Indexes&lt;vars...&gt;::indexesmissing ';' before '&lt;'
  • @xyz 在这里,我使用标准的“indecies 技巧”在 C++11 中完成这项工作:coliru.stacked-crooked.com/a/0113a31abe51b68f。它应该在 VS2013 中工作。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 2020-02-24
  • 2015-04-16
  • 1970-01-01
  • 2011-03-10
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多