Reading binary data with input iterators
<p>I often need to read binary data from different sources like <code>fstream</code>s, <code>vector</code>s, <code>boost::interprocess::mapped_region</code>s, and data returned as simple pointers by C functions among others, so I've been looking at defining a template function to read things like packed POD structs and primitives using iterators, so far I have the following:</p>

<pre><code>template&lt;typename InputIterator, typename T&gt;
InputIterator read(InputIterator first, InputIterator last, T&amp; result)
{
    typedef typename std::iterator_traits&lt;InputIterator&gt;::pointer pointer;
    typedef typename std::iterator_traits&lt;InputIterator&gt;::value_type value_type;

    static_assert(sizeof(value_type) == sizeof(char), "Only valid for byte iterators");

    auto pos = reinterpret_cast&lt;pointer&gt;(&amp;result), end = pos + sizeof result;
    while (pos &lt; end &amp;&amp; first != last)
        *pos++ = *first++;
    if (pos != end)
        result = T();
    return first;
}
</code></pre>

<p>I know this doesn't take endianness into account, but all the data is already in the correct format for the machine.</p>

<p>I thought about using <code>std::copy_n</code> but that risks falling off the end in the case of a <code>std::istreambuf_iterator</code> or any other input iterator as there's no way to check beforehand if there is enough data in the range.</p>

<p>I'm not particularly fond of passing the T in by reference, but I can only return the T or the iterator (I could return a <code>pair</code> with both I suppose).</p>

<p>Is there a better way of going about this? Am I simply trying too hard to find a solution to something that should be handled separately in the first place, i.e. one function for input iterators, one for random access iterators? Or should I just stick to <code>stream::read()</code> for files and <code>std::copy</code> for other iterators, and abandon the idea of having a single template for all sources that makes use of this function?</p>
