C++17可变参数函数调用
时间: 2023-07-11 20:53:21 浏览: 56
C++17中引入了新的语法`constexpr if`和折叠表达式,可以更方便地实现可变参数函数调用。
具体实现方式如下:
1. 定义一个模板函数,函数模板参数包含一个参数包。
2. 在函数体中使用`constexpr if`和折叠表达式来展开参数包,以实现对可变参数的遍历操作。
下面是一个简单的例子,实现可变参数函数的调用:
```c++
#include <iostream>
#include <cstdio>
using namespace std;
template<typename... Args>
void my_printf(const char* fmt, Args... args) {
while (*fmt) {
if (*fmt == '%' && *(fmt + 1) != '%') {
if constexpr (std::is_same_v<int, std::decay_t<decltype(args)>>) {
cout << va_arg(args, int) << endl;
} else if constexpr (std::is_same_v<const char*, std::decay_t<decltype(args)>>) {
cout << va_arg(args, const char*) << endl;
} else {
// Other types
}
fmt += 2;
} else {
cout << *fmt << endl;
fmt++;
}
}
}
int main() {
my_printf("Hello %s!\n", "world");
my_printf("The value of pi is %d.\n", 3);
return 0;
}
```
在上面的例子中,我们定义了一个`my_printf`函数,该函数的第一个参数是一个`const char*`类型的字符串,用于格式化输出,后面的参数是一个可变参数列表,可以是任意类型的值。在函数体中,我们使用了`constexpr if`和折叠表达式来根据参数类型来输出不同的结果。
需要注意的是,在使用可变参数的时候,应该尽量避免类型转换和参数类型不一致的问题,以保证程序的正确性和可读性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)