(23条消息) 变参下标_最后冰吻free的博客-CSDN博客

PHOTO EMBED

Thu Nov 24 2022 06:07:43 GMT+0000 (Coordinated Universal Time)

Saved by @leawoliu

#include <iostream>
#include <string>
#include <vector>
 
 // 参数下标:遍历容器,可以根据自定义下标顺序进行访问
 
 
 template<typename First, typename... Args>
 void Print(First first, Args... args){
     std::cout<<first<<std::endl;
     if constexpr (sizeof...(args)> 0) {
         Print(args...);
     }
 }
 
// 变参下标 
template<typename T, typename... Idxs>
void PrintElems(T& t, Idxs... idx) {
    Print(t[idx]...);
}

void Test(){
    std::vector<int> v{1,2,3,4};
    PrintElems(v, 0,3,2,1);// 扩展开相当于调用Print(v[0], v[3], v[2], v[1]);
}

// 使用非类型模板参数声明为参数包
template<std::size_t... Idxs, typename T>
void PrintElems(T& t){
    Print(t[Idxs]...);
}

void Test1(){
    std::vector<std::string> v{"ts","js","c++"};
    PrintElems<2,0,1>(v);
}


int main()
{
    Test();
    Test1();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
content_copyCOPY

https://blog.csdn.net/CodeHouse/article/details/126346185