I'm trying to use a stream in order to read from a vector of existing data.
// http://stackoverflow.com/questions/8815164/c-wrapping-vectorchar-with-istream
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT>
{
public:
vectorwrapbuf(std::vector<CharT> &vec)
{
this->setg(&vec[0], &vec[0], &vec[0] + vec.size());
}
};
int main()
{
vector<char> data(100, 1);
vectorwrapbuf<char> databuf(data);
std::istream file(&databuf);
file.exceptions(std::istream::failbit | std::istream::badbit);
file.seekg(10); // throws
}
However when I call seekg
it throws an exception (or reports error normally if not using exceptions). Why is this? 10 is within the 100 chars of input data.
Code needs to work with both C++11 and before compilers.
Live example: http://ideone.com/PfpW0o