fork download
  1. // http://stackoverflow.com/a/28240199/146041
  2. #include<iostream>
  3. using namespace std;
  4. template<typename T, size_t N>
  5. auto convert( T (&t) [N] ) -> T* {
  6. //cout << __PRETTY_FUNCTION__ << endl;
  7. return t; // just let pointer decay work for us here
  8. }
  9. template<typename T>
  10. auto convert( T &t) -> T* {
  11. //cout << __PRETTY_FUNCTION__ << endl;
  12. return &t;
  13. }
  14.  
  15. template<typename T, size_t N>
  16. auto convert_end( T (&t) [N] ) -> T* {
  17. //cout << __PRETTY_FUNCTION__ << endl;
  18. return ((T*)t)+N; // just let pointer decay work for us here
  19. }
  20. template<typename T>
  21. auto convert_end( T &t) -> T* {
  22. //cout << __PRETTY_FUNCTION__ << endl;
  23. return (&t)+1;
  24. }
  25.  
  26. template<typename T>
  27. void iterate_test(T&& t) {
  28. int * b = convert(t);
  29. int * e = convert_end(t);
  30. cout << "(number of elements): " << (e-b) << endl;
  31. while(b<e) {
  32. cout << *b << endl;
  33. ++b;
  34. }
  35. }
  36.  
  37. int main() {
  38. int i = 10;
  39. int a1i[1] = {100};
  40. int a3i[3] = {1,2,3};
  41.  
  42. iterate_test(i);
  43. iterate_test(a1i);
  44. iterate_test(a3i);
  45. }
  46.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
(number of elements): 1
10
(number of elements): 1
100
(number of elements): 3
1
2
3