C++可变参数模板
# 模板参数包
# 概念
模板参数包就是把若干个模板参数打包成一个。
template <typename... T> //声明一个类型为... 的T, 就是一个模板参数包
void f(T... args);
1
2
2
可以把...看成类型说明符,类似于*。
# 包扩展表达式
参考: https://www.cnblogs.com/Glucklichste/p/11175769.html (opens new window)
设args被声明为一个函数参数包,其扩展方式有
printArgs(args…) 相当于printArgs(args1,args2,…,argsN)
printArgs(args)… 相当于printArgs(args1),…, printArgs(argsN)
(printArgs(args),0)… 逗号表达式 这是一个逗号表达式。相当于(printArgs(args1),0),…(printArgs(argsN),0) 包扩展表达式“exp…”相当于将省略号左侧的参数包exp视为一个整体来进行扩展
当声明一个变量(或标识符)为可变参数时,省略号位于该变量的左侧 当使用参数包时,省略号位于参数名称的右侧,表示立即展开该参数,这个过程也被称为解包
# 示例
template <typename T>
class Storage {
private:
T* p;
public:
template <typename... Args>
Storage(Args &&... args) {
p = new T(std::forward<Args>(args)...);
//相当于 std::forward(args1),…, printArgs(argsN)
}
};
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 可变模版参数函数和可变模版参数类
# 泛化展开
参考: https://www.cnblogs.com/qicosmos/p/4325949.html (opens new window)
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
using namespace std;
template<typename... Args>
static inline std::string get_first_exist_file(Args ...args)
{
std::vector<std::string> filenames{args...};
for(auto p = filenames.begin(); p != filenames.end(); ++p) {
if(fopen(p->c_str(), "r"))
return *p;
}
return std::string();
}
int main() {
auto first_file = get_first_exist_file("aa.txt", "bb.txt");
printf("first_file=%s\n", first_file.c_str());
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2023/05/07, 17:27:54