From ebab8cab7f552e0fa2265f940e1dab2fdb6551d2 Mon Sep 17 00:00:00 2001 From: Casey Carter Date: Mon, 3 Apr 2017 22:43:43 -0700 Subject: gsl::at clean-up: (#479) * initializer_list overload returns by value to avoid lifetime issues * generic overload uses expression SFINAE to work with any type that has member size() and operator[], which notably includes const/non-const vector and array. * Add test coverage for const objects, rvalue initializer_lists, and constexpr usage. Fixes #357. --- include/gsl/gsl_util | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) (limited to 'include/gsl/gsl_util') diff --git a/include/gsl/gsl_util b/include/gsl/gsl_util index 8961539..24c35e0 100644 --- a/include/gsl/gsl_util +++ b/include/gsl/gsl_util @@ -127,31 +127,25 @@ inline T narrow(U u) } // -// at() - Bounds-checked way of accessing static arrays, std::array, std::vector +// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector // template -inline constexpr T& at(T (&arr)[N], std::ptrdiff_t index) -{ - Expects(index >= 0 && index < narrow_cast(N)); - return arr[static_cast(index)]; -} - -template -inline constexpr T& at(std::array& arr, std::ptrdiff_t index) +inline constexpr T& at(T (&arr)[N], const std::ptrdiff_t index) { Expects(index >= 0 && index < narrow_cast(N)); return arr[static_cast(index)]; } template -inline constexpr typename Cont::value_type& at(Cont& cont, std::ptrdiff_t index) +inline constexpr auto at(Cont& cont, const std::ptrdiff_t index) -> decltype(cont[cont.size()]) { Expects(index >= 0 && index < narrow_cast(cont.size())); - return cont[static_cast(index)]; + using size_type = decltype(cont.size()); + return cont[static_cast(index)]; } template -inline constexpr const T& at(std::initializer_list cont, std::ptrdiff_t index) +inline constexpr T at(const std::initializer_list cont, const std::ptrdiff_t index) { Expects(index >= 0 && index < narrow_cast(cont.size())); return *(cont.begin() + index); -- cgit v1.2.3