cpp几种可变参数包展开方法

  • 递归
void print(){
	std::cout << "\n";
}

template<typename T, typename... Args>
void print(T a, Args... args){
	std::cout << a << " ";
	print(args...);
}

template<typename... Args>
void test(Args... args){
	print(args...);
}
  • enable_if
template<size_t t = 0, typename tup>
typename enable_if<t == std::tuple_size<tup>::value>::type print(tup tup_entity){
    cout << "\n";
}

template<size_t t = 0, typename tup>
typename enable_if<t < std::tuple_size<tup>::value>::type print(tup tup_entity){
    cout << get<t>(tup_entity) << " ";
    print<t + 1>(tup_entity);
}

template<typename... Args>
void test(Args... args){
    print(make_tuple(args...));
}
  • 逗号表达式,只要是有序的初始化都可以,int数组,初始化列表等
template<typename... Args>
void test(Args... args){
    int a[]{(cout << args << " ",0)...};
    cout << endl;
    // 或
    initializer_list<int>{(cout << args << " ", 0)...};
    cout << endl;
}
  • index_sequence、index_sequence_for、make_index_sequence
template<typename Tuple, size_t I>
void print_t_impl(Tuple tup){
    cout << get<I>(tup) << " ";
}

template<typename Tuple, size_t... I>
void print_t(Tuple tup, index_sequence<I...>){
    int a[]{(print_t_impl<Tuple, I>(tup), 0)...};
    cout << endl;
}

template<typename... Args>
void test(Args... args){
    auto tupe = make_tuple(args...);
    
    print_t(tupe, make_index_sequence<sizeof...(args)>{});
    // 或
    print_t(tupe, index_sequence_for<Args...>{});
	// 或
	using Args_type = tuple<typename decay<Args>::type...>;
    constexpr auto N = tuple_size<typename decay<Args_type>::type>::value;
    print_t(tupe, make_index_sequence<N>{});
    // 或
    constexpr auto NN = tuple_size<typename decay<decltype(tupe)>::type>::value;
    print_t(tupe, make_index_sequence<N>{});
}

你可能感兴趣的:(c++,数据结构)