code_junkie

Can someone explain this template code that gives me the size of an array?

Nov 13th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. template<typename T, size_t n>
  2. size_t array_size(const T (&)[n])
  3. {
  4. return n;
  5. }
  6.  
  7. int a[] = {1, 2, 3};
  8. int *ap = a; // a pointer, size is lost
  9. int (&ar)[3] = a; // a reference to the array, size is not lost
  10.  
  11. template<typename T, size_t n>
  12. size_t array_size(const T (&)[n]) {
  13. return n;
  14. }
  15.  
  16. size_t array_size(const int (&)[3]) {
  17. return 3;
  18. }
  19.  
  20. size_t size_of_a = array_size(a);
  21.  
  22. template<typename T, size_t n>
  23. char (& array_size(const T (&)[n]) )[n];
  24.  
  25. size_t size_of_a = sizeof(array_size(a));
  26.  
  27. int havingSameSize[sizeof(array_size(a))];
  28.  
  29. // Note that you don't need to name the array, since you don't
  30. // actually reference the parameter at all.
  31. size_t array_size(const int (&)[1])
  32. {
  33. return 1;
  34. }
  35.  
  36. size_t array_size(const int (&)[2])
  37. {
  38. return 2;
  39. }
  40.  
  41. size_t array_size(const int (&)[3])
  42. {
  43. return 3;
  44. }
  45. // etc...
  46.  
  47. int a[2];
  48. array_size(a);
  49.  
  50. template <int n>
  51. size_t array_size(const int (&)[n])
  52. {
  53. return n;
  54. }
  55.  
  56. template <typename T, int n>
  57. size_t array_size(const T (&)[n])
  58. {
  59. return n;
  60. }
  61.  
  62. const int &a[1];
  63.  
  64. const int (&a)[1];
  65.  
  66. size_t array_size(const int (&)[1])
  67.  
  68. char a[10];
  69. array_size(a); // returns 10
Add Comment
Please, Sign In to add comment