c++多参数
时间: 2023-06-29 16:12:07 浏览: 65
在C++中,函数可以接受多个参数,可以使用以下几种方式:
1. 用逗号隔开多个参数,例如:
```c++
void func(int a, int b, int c) {
// ...
}
func(1, 2, 3);
```
2. 使用结构体或类封装多个参数,例如:
```c++
struct Point {
int x;
int y;
};
void func(Point p) {
// ...
}
func({1, 2});
```
3. 使用可变参数模板(variadic templates)实现接受任意数量和类型的参数,例如:
```c++
#include <iostream>
void print() {}
template<typename T, typename... Args>
void print(T t, Args... args) {
std::cout << t << ' ';
print(args...);
}
int main() {
print(1, 2.0, "hello");
return 0;
}
```
上面的代码中,`print()`函数可以接受任意数量和类型的参数,使用递归实现了多参数的打印功能。
使用可变参数模板还可以实现更复杂的多参数操作,例如:
```c++
#include <iostream>
#include <tuple>
template<typename F, typename Tuple, size_t... I>
decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) {
return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
}
template<typename F, typename Tuple>
decltype(auto) apply(F&& f, Tuple&& t) {
using Indices = std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value>;
return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices{});
}
int add(int a, int b) {
return a + b;
}
int main() {
auto t = std::make_tuple(1, 2);
std::cout << apply(add, t) << std::endl;
return 0;
}
```
上面的代码中,`apply()`函数可以接受任意数量和类型的参数,使用`std::tuple`封装参数,并使用可变参数模板实现了参数展开和调用指定的函数。