fork(2) download
  1. #include <array>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. template <typename T>
  6. struct size_getter {
  7. static size_t getSize( T );
  8. };
  9.  
  10. template <typename T>
  11. void serialize(const T &data)
  12. {
  13. size_t data_size = size_getter<T>::getSize( data );
  14. std::cout << "Size: " << data_size << std::endl;
  15. }
  16.  
  17. template<>
  18. struct size_getter<int> {
  19. static constexpr size_t getSize( int )
  20. {
  21. return sizeof(int);
  22. }
  23. };
  24.  
  25. template<>
  26. struct size_getter<std::string> {
  27. static size_t getSize( const std::string &s )
  28. {
  29. return s.size();
  30. }
  31. };
  32.  
  33. template <typename T, size_t N>
  34. struct size_getter<std::array<T, N>>
  35. {
  36. static size_t getSize(const std::array<T, N> &array)
  37. {
  38. size_t array_size = 0;
  39. for (const T &element : array)
  40. array_size += size_getter<T>::getSize(element);
  41. return array_size;
  42. }
  43. };
  44.  
  45. int main()
  46. {
  47. int a;
  48. serialize(a);
  49.  
  50. std::string str = "foo";
  51. serialize(str);
  52.  
  53. std::array<std::string, 2> arr = {{"foo", "foobar"}};
  54. serialize(arr);
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 4192KB
stdin
Standard input is empty
stdout
Size: 4
Size: 3
Size: 9