CPP Homework 04
Exercise from OTUS C++ developer course.
print_ip.h
Go to the documentation of this file.
1 #ifndef PRINT_IP_H
2 #define PRINT_IP_H
3 
4 #include <iostream>
5 #include <list>
6 #include <string>
7 #include <tuple>
8 #include <type_traits>
9 #include <vector>
10 
11 #include "helpers.h"
12 #include "traits.h"
13 
21 template <
22  typename T,
23  std::enable_if_t<std::is_integral_v<T>, int> = 0>
24 void print_ip(T t, std::ostream &stream = std::cout) {
25  constexpr size_t type_size { sizeof(T) };
26 
27  union {
28  unsigned char bytes[type_size];
29  T value;
30  };
31 
32  value = t;
33 
34  for (int i { type_size - 1 }; i >= 0; i--) {
35  stream << to_string(bytes[i]);
36  if (i != 0) stream << '.';
37  }
38  stream << std::endl;
39 }
40 
49 template <
50  typename T,
51  std::enable_if_t<
52  is_iterable_v<T> && !std::is_same_v<T, std::string>,
53  int> = 0>
54 void print_ip(T const &t, std::ostream &stream = std::cout) {
55  auto begin { t.cbegin() };
56  auto end { t.cend() };
57  for (auto it { begin }; it != end; it++) {
58  if (it != begin) stream << '.';
59  stream << to_string(*it);
60  }
61  stream << std::endl;
62 }
63 
73 template <
74  typename T,
75  std::enable_if_t<is_specialisation_of_v<std::tuple, T>, int> = 0>
76 void print_ip(T const &t, std::ostream &stream = std::cout) {
77  print_ip_tuple_impl(t, stream);
78 }
79 
86 template <
87  typename T,
88  std::enable_if_t<std::is_same_v<T, std::string>, int> = 0>
89 void print_ip(T const &t, std::ostream &stream = std::cout) {
90  stream << t << std::endl;
91 }
92 
99 template <
100  typename T,
101  std::enable_if_t<std::is_same_v<T, const char*>, int> = 0>
102 void print_ip(T t, std::ostream &stream = std::cout) {
103  stream << t << std::endl;
104 }
105 
106 #endif
std::string to_string(T t)
Wrapper function to make string.
Definition: helpers.h:17
void print_ip_tuple_impl(std::tuple< T1, T2 > const &t, std::ostream &stream=std::cout)
Pretty print IP address.
Definition: helpers.h:59