![](/img/trans.png)
[英]How can I initialize an std::array of a class without a default constructor?
[英]How to create a std::array with std::transform without default constructor
我有一個std::array<Foo, 10>
,我想使用Foo
到Bar
的函數創建一個std::array<Bar, 10>
。 通常我會像這樣使用std::transform
:
array<Bar, 10> bars;
transform(foos.begin(), foos.end(), bars.begin(), [](Foo foo){
return Bar(foo.m_1, foo.m_2);
});
但是, Bar
沒有默認構造函數,因此我無法創建bars
數組。 我總是可以使用vector
但是能夠使用array
來保證我總是有10個元素會很好。 那可能嗎?
不是用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
和朋友是C ++ 14,但在C ++ 11中很容易實現。 僅在SO上可能有六個實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.