首页 > 代码库 > C++ 遍历可变模板参数 iterate variadic template arguments

C++ 遍历可变模板参数 iterate variadic template arguments

 1 template<size_t I = 0, typename FuncT, typename ...Tp>
 2 inline typename std::enable_if_t<I == sizeof ...(Tp)> for_each(std::tuple<Tp ...>&, FuncT)
 3 {
 4 }
 5 
 6 template<size_t I = 0, typename FuncT, typename ...Tp>
 7 inline typename std::enable_if_t<I < sizeof ...(Tp)> for_each(std::tuple<Tp ...>& t, FuncT f)
 8 {
 9     f(std::get<I>(t));
10     for_each<I + 1, FuncT, Tp...>(t, f);
11 }
12 
13 template<typename ...Args>
14 auto print(Args ...args)
15 {
16     auto a = std::forward_as_tuple(args...);
17     for_each(a, [](auto x)
18     {
19         std::cout << typeid(x).name() << ":" << x << std::endl;
20     });
21 }
22 
23 int main()
24 {
25     print(10, c, "bbb", string("123"));
26 }

结果如下:

int:10
char:c
char const *:bbb
class std::basic_string<char, struct std::char_traits<char>, class std::allocator<char> >:123

C++ 遍历可变模板参数 iterate variadic template arguments