Advertisement
Guest User

Untitled

a guest
Jul 6th, 2016
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <tuple>
  4. #include <type_traits>
  5.  
  6. //we use std::enable_if to specify the end condition
  7. template<size_t I, typename... Tp>
  8. typename std::enable_if<I == sizeof...(Tp), void>::type
  9. print_tuple(std::tuple<Tp...> const&)
  10. {
  11. }
  12.  
  13. //This is one of the solution to write
  14. //compile time loop in c++
  15. //std::enable_if work because c++ follow the rule of
  16. //"SFINAE"(you can check it if you are interesting about it)
  17. //the second parameter of enable_if is the type itself
  18. template<size_t I = 0, typename... Tp>
  19. typename std::enable_if<I < sizeof...(Tp), void>::type
  20. print_tuple(std::tuple<Tp...> const &tuples)
  21. {
  22.     std::cout<<std::get<I>(tuples)<<std::endl;
  23.     print_tuple<I+1>(tuples);
  24. }
  25.  
  26. int main()
  27. {
  28.     //exactly, when you specify your types by tuples like this(by template)
  29.     //the compiler already know your type at compile time
  30.     //Maybe we can said that, everything related to template must be known at
  31.     //compile time, it is a pure compile time infrastructure
  32.     std::tuple<std::string, int, float, double> const tuples(
  33.             "one", 2, 3.0f, 4.0);
  34.     print_tuple(tuples);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement