是否可以将下面的长显式初始化列表替换为某个生成它的模板?
std::array<Foo, n_foos> foos = {{
{0, bar},
{1, bar},
{2, bar},
{3, bar},
{4, bar},
{5, bar},
{6, bar},
{7, bar},
}};
现在这段代码之所以有效,是因为我们有 constexpr int n_foos = 8
。对于任意大的 n_foos
如何做到这一点?
最佳答案
以下解决方案使用 C++14 std::index_sequence
和 std::make_index_sequence
(can be easily implemented in C++11 program):
template <std::size_t... indices>
constexpr std::array<Foo, sizeof...(indices)>
CreateArrayOfFoo(const Bar& bar, std::index_sequence<indices...>)
{
return {{{indices, bar}...}};
}
template <std::size_t N>
constexpr std::array<Foo, N> CreateArrayOfFoo(const Bar& bar)
{
return CreateArrayOfFoo(bar, std::make_index_sequence<N>());
}
// ...
constexpr std::size_t n_foos = 8;
constexpr auto foos = CreateArrayOfFoo<n_foos>(bar);
参见 live example .
关于c++ - 如何使用常规构造函数模式初始化 C++ 11 标准容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25312468/