C++ 遍历可变模板参数 iterate variadic templat…

2018-06-17 22:57:14来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 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

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:堆排序

下一篇:读书笔记 effective c++ Item 41 理解隐式接口和编译期多态