Bee*_*ope 2 c++ variadic-templates c++11
考虑以下非类型可变参数模板函数:
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);
}
Run Code Online (Sandbox Code Playgroud)
它使用递归方法在模板参数包中指定的偏移量处写入 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);
Run Code Online (Sandbox Code Playgroud)
使用 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);
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           71 次  |  
        
|   最近记录:  |