exception handling iterator interface
I'm trying to make a watertight interface to a library that I'm designing. The user is to enter two dimensional data and so I thought an iterator interface similar to std::transform
would be transparant.
However, I am unsure how to exception handle any abuse of the iterators.
My interface is like so (I can change the interface if there is a better one):
template<typename InputItrX, typename InputItrY>
set_data(InputItrX beginX, InputItrX endX, InputItrY beginY)
{
//What exception handling should I do here?
size_t array_size = endX-beginX; //get the size of the xarray.
my_xVector.resize(array_size); //resize my internal container
my_yVector.resize(array_size); // ..and for the ydata.
std::copy(beginX, endX, my_xVect开发者_Go百科or.begin()); //copy X
std::copy(beginY, beginY+array_size, my_yVector.begin()); //copy Y
}
For example, my program becomes undefined if the user get muddled up with the interface and writes
set_data(xdata.begin(), ydata.begin(), xdata.end());
or maybe their xdata
has 20 elements but their ydata
has none.
Is it possible to check for such mistakes in my library interface?
I wouldn't add any checks to the method, but document that the exception specification depends on the used iterators. So the user can use checked iterators if he doesn't care about performance losses or unchecked iterators and get best performance. I think most implementations of STL iterators has asserts that check for iterator incompatibilities. Theses errors don't need check in release mode, because they are programmer mistakes.
size_t array_size = endX-beginX; //get the size of the xarray.
my_xVector.resize(array_size); //resize my internal container
my_yVector.resize(array_size); // ..and for the ydata.
This makes your method incompatible with iterators that don't have the -operator! It can be used only with random access iterator. You should extract this to a resize_vectors template which can be implemented for random access iterators, but doesn't make any resize for other iterators. In the std::copy
you have to use an inserter iterator that resizes the vector, while inserting if the vectors don't have enough capacity.
精彩评论