fork(5) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<size_t Index, size_t N>
  5. constexpr bool checkArrayBounds()
  6. {
  7. return Index < N || (throw "Index out of bounds", false);
  8. }
  9.  
  10. template<size_t Index, typename T, size_t N>
  11. constexpr T array_at(T(&array)[N]) // `array` is a reference to `T[N]`
  12. {
  13. return checkArrayBounds<Index, N>(), *(array+Index); // Comma magic *-*
  14. }
  15.  
  16. int main()
  17. {
  18. constexpr int x[] { 1, 2, 3 };
  19.  
  20. static_assert(array_at<0>(x) == 1, "Error");
  21. static_assert(array_at<1>(x) == 2, "Error");
  22. static_assert(array_at<2>(x) == 3, "Error");
  23.  
  24. cout << array_at<0>(x) << endl;
  25. cout << array_at<1>(x) << endl;
  26. cout << array_at<2>(x) << endl;
  27.  
  28. return 0;
  29. }
Success #stdin #stdout 0s 4440KB
stdin
Standard input is empty
stdout
1
2
3