|
Boost Users : |
Subject: [Boost-users] [array] range check (at compile time)
From: alfC (alfredo.correa_at_[hidden])
Date: 2010-02-19 23:35:43
Hi,
Lately I find myself using boost::array intesively, specially in
small demo programs. Sometimes, when "manually" accessing the elements
I type a index out of range. The library can detect these errors once
the program is running but I found this a waste, also I was surprised
not to see this kind of static check not implemented in the library.
So I wanted to see if I could enforce range checking at compile time,
and I come out with this solution.
namespace boost{ //sorry about the namespace name
template<size_t IDX, typename T, size_t N>
const T& get(boost::array<T, N> const& arr){
BOOST_STATIC_ASSERT(IDX<N);
return arr[IDX];
}
template<size_t IDX, typename T, size_t N>
T& get(boost::array<T, N>& arr){
BOOST_STATIC_ASSERT(IDX<N);
return arr[IDX];
}
}
#include<iostream>
void main(){
boost::array<double, 3> a = {1,2,3};
std::clog<<boost::get<2>(a)<<std::endl; // ok, (namespace
specification needed, why?)
std::clog<<boost::get<5>(a)<<std::endl; //does not compile
return 0;
}
(I though about using enable_if instead of BOOST_STATIC_ASSERT but
that would be too much overengineering.)
Is this implemented already in some other way?
Alfredo
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net