[英]How to create a std::array with std::transform without default constructor
I have a std::array<Foo, 10>
and I would like to create a std::array<Bar, 10>
using a function from Foo
to Bar
. 我有一个
std::array<Foo, 10>
,我想使用Foo
到Bar
的函数创建一个std::array<Bar, 10>
。 Ordinarily I would use std::transform
like so: 通常我会像这样使用
std::transform
:
array<Bar, 10> bars;
transform(foos.begin(), foos.end(), bars.begin(), [](Foo foo){
return Bar(foo.m_1, foo.m_2);
});
However, Bar
doesn't have a default constructor, so I can't create the bars
array. 但是,
Bar
没有默认构造函数,因此我无法创建bars
数组。 I could always use vector
but it would be nice to be able to use array
to guarantee that that I always have exactly 10 elements. 我总是可以使用
vector
但是能够使用array
来保证我总是有10个元素会很好。 Is that possible? 那可能吗?
Not with std::transform
, but nothing a little template magic can't fix. 不是用
std::transform
,但没有一点模板魔法无法修复。
template<std::size_t N, std::size_t... Is>
std::array<Bar, N> foos_to_bars(const std::array<Foo, N>& foos,
std::index_sequence<Is...>) {
return {{ Bar(foos[Is].m_1, foos[Is].m_2)... }};
}
template<std::size_t N, std::size_t... Is>
std::array<Bar, N> foos_to_bars(const std::array<Foo, N>& foos) {
return foos_to_bars(foos, std::make_index_sequence<N>());
}
std::index_sequence
and friends are C++14, but easily implementable in C++11. std::index_sequence
和朋友是C ++ 14,但在C ++ 11中很容易实现。 There are probably half a dozen implementations on SO alone. 仅在SO上可能有六个实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.