diff --git a/array.h b/array.h index 1bde0a43..63f68c2a 100644 --- a/array.h +++ b/array.h @@ -37,6 +37,7 @@ SOFTWARE. #include "exception.h" #include "type_traits.h" #include "parameter_type.h" +#include "static_assert.h" #ifndef ETL_THROW_EXCEPTIONS #include "error_handler.h" @@ -468,6 +469,36 @@ namespace etl rhs.cbegin(), rhs.cend()); } + + //************************************************************************* + /// Gets a reference to an element in the array. + ///\tparam I The index. + ///\tparam T The type. + ///\tparam N The array size. + ///\param a The array. + ///\return A reference to the element + //************************************************************************* + template + inline T& get(array& a) + { + STATIC_ASSERT(I < N, "Index out of bounds"); + return a[I]; + } + + //************************************************************************* + /// Gets a const reference to an element in the array. + ///\tparam I The index. + ///\tparam T The type. + ///\tparam N The array size. + ///\param a The array. + ///\return A const reference to the element + //************************************************************************* + template + inline const T& get(const array& a) + { + STATIC_ASSERT(I < N, "Index out of bounds"); + return a[I]; + } } #endif diff --git a/test/test_array.cpp b/test/test_array.cpp index 91b57784..732fb505 100644 --- a/test/test_array.cpp +++ b/test/test_array.cpp @@ -333,6 +333,19 @@ namespace CHECK(std::equal(swap_data.begin(), swap_data.end(), data2.begin())); } + //************************************************************************* + TEST(test_get) + { + Data data1 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + const Data data2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + + CHECK_EQUAL(data1[3], etl::get<3>(data1)); + CHECK_EQUAL(data2[3], etl::get<3>(data2)); + + // The following line should fail with a compile error. + //int i = etl::get<11>(data2); + } + //************************************************************************* TEST(test_equal) {