您可以使用std::index_sequence
获取数组的索引作为非类型模板参数包。然后就可以使用参数包扩展了。
template<size_t Size>
struct Foo {
int const myVals[Size];
Foo(std::array<Input, Size> const &in)
: Foo(in, std::make_index_sequence<Size>()) { }
private:
template<size_t... Is>
Foo(std::array<Input, Size> const &in, std::index_sequence<Is...>)
: myVals{in[Is].value...} { }
}
使用辅助模板size_t... Is
包和一个std::index_sequence<Is...>
参数是处理固定大小可索引容器的常见模式。这index_sequence
实际上什么也没做;它只是一个代理,因此Is
可以推导出模板参数。例如。如果你检查Godbolt https://www.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,lang:c%2B%2B,source:'%23include+%3Carray%3E%0A%0Astruct+Input+%7B%0A++++int+value%3B%0A%7D%3B%0A%0Atemplate%3Csize_t+Size%3E%0Astruct+Foo+%7B%0A++++int+const+myVals%5BSize%5D%3B%0A++++Foo(std::array%3CInput,+Size%3E+const+%26in)%0A++++++++:+Foo(in,+std::make_index_sequence%3CSize%3E())+%7B+%7D%0A++++private:%0A++++template%3Csize_t...+Is%3E%0A++++Foo(std::array%3CInput,+Size%3E+const+%26in,+std::index_sequence%3CIs...%3E)%0A++++++++:+myVals%7Bin%5BIs%5D.value...%7D+%7B+%7D%0A%7D%3B%0A%0Aint+main()+%7B%0A++++Foo%3C2%3E+f(std::array%3CInput,+2%3E%7B%7B%7B1%7D,+%7B2%7D%7D%7D)%3B%0A%7D'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:54.29831006612784,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:clang800,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:1.0749542399999998,lang:c%2B%2B,libs:!(),options:'-std%3Dc%2B%2B2a+-Wall+-O1',source:1),l:'5',n:'0',o:'x86-64+clang+8.0.0+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:45.70168993387216,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4它似乎完全蒸发了-O1
.