可变参数模板的无递归扩展到数组访问

考虑以下非类型可变参数模板函数:

template <typename dummy = void>
void write_at_offsets(volatile char *p) {
}

template <size_t OFF, size_t... OFFs>
void write_at_offsets(volatile char *p) {
    p[OFF] = 1;
    write_at_offsets<OFFs...>(p);
}

它使用递归方法在模板参数包中指定的偏移量处写入 1。

这是否可以在 C++11 中不使用递归而简洁地编写,例如,通过一次性扩展整个包?

回答

您可以使用折叠表达式(c++17 起),在 中传递偏移量index_sequence

template<size_t ... Indices>
void foo(std::index_sequence<Indices...>,volatile char* p){
    ( (p[Indices] = 1),... );
}

int main(){
    char* p = new char[3];
    foo(std::index_sequence<0,1,2>(),p);

使用 C++11 创建由 0 填充的假数组,并使用逗号表达式(Calculation,0)

template<size_t ... Indices>
void foo(char* p, const int val){
    int fake[] = { (p[Indices] = val,0)... };
    // cast fake to void to prevent compiler warning present
}

int main(){
    char* p = new char[3];
    foo<0,1,2>(p,48);

  • Wouldn't it work without the `std::index_sequence` as well? (I mean - to resemble OPs code closer.) I fiddled with your example: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/c9000c713c15a366)

以上是可变参数模板的无递归扩展到数组访问的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>