Advertisement
GeneralGDA

Static Array Length Without Macros

Feb 13th, 2015
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. #include "stdafx.h"
  2.  
  3. template<typename T>
  4. struct Length final
  5. {
  6.     static const int value = sizeof(T) / sizeof(std::remove_extent<T>::type);
  7.  
  8.     static_assert ( std::is_array<T>::value, "can evaluate size only for arrays" );
  9.  
  10.     Length() = delete;
  11.     Length(const Length&) = delete;
  12.     Length& operator=(const Length&) = delete;
  13. };
  14.  
  15. int _tmain(int, _TCHAR*)
  16. {  
  17.     const int a[] = { 1, 2, 3, 4 };
  18.  
  19.     std::cout << Length<decltype(a)>::value << std::endl;
  20.  
  21.     for (auto i = 0; i < Length<decltype(a)>::value; ++i)
  22.     {
  23.         std::cout << a[i] << std::endl;
  24.     }
  25.  
  26.     return 0;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement