template<typename T> void fun2(T t) { cout << t << endl; } //利用逗号表达式和初始化列表展开 template<typename ...Arg6> void fun1(Arg6... args) { int arr[] = { (fun2(args),0)... }; } template<typename T> int func3Imp(T&& t) { static int c = 0; std::cout << t << endl; return ++c; } template<typename... Ts> void func3(Ts&&... args) { const int size = sizeof...(args) + 2; int res[size] = { 1, args..., 2 }; //初始化列表展开 int dummy[sizeof...(Ts)] = { func3Imp(std::forward<Ts>(args))...}; } template<class... Args> void fLambda(Args... args) { //注意这里调用func3(args...),属于参数包直接展开为func3的参数 auto lm = [&, args...] { return func3(args...); }; lm(); } template<typename... Ts, int... N> void print_tuple(const std::tuple<Ts...>& t, std::index_sequence<N...>) { int dummy[sizeof...(Ts)] = { func3Imp(std::get<N>(t))... }; // 初始化列表展开,和index_sequence配合使用 //fLambda(std::get<N>(t)...); //参数包在函数形参中的展开 fLambda(std::get<1>(t),std::get<2>(t),std::get<3>(t)) //fLambda(func3Imp(std::get<N>(t))...); //fLambda(func3Imp(std::get<1>(t)),func3Imp(std::get<2>(t)),func3Imp(std::get<3>(t))) } template<typename... Ts, int... N> void print_tuple2(const std::tuple<Ts...>& t, std::index_sequence<N...>) { int dummy[sizeof...(Ts)] = { (func3Imp(std::get<N>(t)),0)... };//利用逗号表达式和初始化列表展开 } template<typename... Ts, int... N> void print_tuple3(const std::tuple<Ts...>& t, std::index_sequence<N...>) { // ((std::cout << std::get<N>(t) << ' '), ...); //c++17的折叠表达式 } //使用 { //auto tuple = std::make_tuple(1, 2.3, "hello"); auto tuple = std::make_tuple(1, 2, 333); print_tuple(tuple, std::make_index_sequence<std::tuple_size_v<decltype(tuple)>>{}); //make_index_sequence的参数必须<=tuple元素数量 print_tuple2(tuple, std::make_index_sequence<std::tuple_size_v<decltype(tuple)>>{}); print_tuple3(tuple, std::make_index_sequence<std::tuple_size_v<decltype(tuple)>>{}); } fun1(12, 3, 4); func3(12, 13); fLambda(11, 12);
参考:https://zh.cppreference.com/w/cpp/language/parameter_pack
标签:std,...,func3Imp,get,int,折叠,args,c++,表达式 From: https://www.cnblogs.com/Cxiangyang/p/18298799