c++ - Why std::is_same does not work? -
my code snippet is:
namespace serialization { struct output_stream { ///// void write(const void* data, size_t size) { const byte_t* p = static_cast<const byte_t*>(data); size_t old_size = buffer_.size(); buffer_.resize(old_size + size); memcpy(buffer_.data() + old_size, p, size); } } struct input_stream { /////// void read(void* to, size_t size) { assert(cur_ + size <= end_); memcpy(to, cur_, size); cur_ += size; } } } template <class stream_t> void serialize(not_pod_struct& r, stream_t stream) { if (std::is_same<stream_t, serialization::output_stream>::value) { stream.write(&r, sizeof(r)); } else if (std::is_same<stream_t, serialization::input_stream>::value) { not_pod_struct* buf = new not_pod_struct[sizeof(not_pod_struct)]; stream.read(buf, sizeof(not_pod_struct)); r = *buf; } else { throw std::invalid_argument("stream_t not stream."); } } template<class t> typename enable_if<!is_pod<t>::value, void>::type read(input_stream & input_stream, t & non_pod_struct) { serialize(non_pod_struct, input_stream); } template<class t> typename enable_if<!is_pod<t>::value, void>::type write(output_stream & output_stream, t & non_pod_struct) { serialize(non_pod_struct, output_stream); }
i have errors:
error 1 error c2039: 'read' : not member of 'serialization::output_stream' error 2 error c2039: 'write' : not member of 'serialization::input_stream'
this strange. not understand why these errors happen.
if
not static if
in other languages. branch not reached still must compile.
tag dispatch (this more useful if doing more complicated is_same
(e.g., accept various streams based on is_input_stream
trait); there's not point in using template accepts 2 types , different things each):
template <class stream_t> void serialize(not_pod_struct& r, stream_t & stream, std::true_type /* is_input */, std::false_type /* is_output */) { not_pod_struct* buf = new not_pod_struct[sizeof(not_pod_struct)]; stream.read(buf, sizeof(not_pod_struct)); r = *buf; } template <class stream_t> void serialize(not_pod_struct& r, stream_t & stream, std::false_type /* is_input */, std::true_type /* is_output */) { stream.write(&r, sizeof(r)); } template <class stream_t> void serialize(not_pod_struct& r, stream_t & stream) { serialize(r, stream, std::is_same<stream_t, serialization::input_stream>(), std::is_same<stream_t, serialization::output_stream>()); }
or overload serialize
output_stream
, input_stream
:
void serialize(not_pod_struct& r, serialization::input_stream & stream) { not_pod_struct* buf = new not_pod_struct[sizeof(not_pod_struct)]; stream.read(buf, sizeof(not_pod_struct)); r = *buf; } void serialize(not_pod_struct& r, serialization::output_stream & stream) { stream.write(&r, sizeof(r)); }
i took liberty of having serialize
accept stream reference. also, don't think "read" logic correct. not leak memory allocated new
, i'm extremely doubtful meant allocate array of sizeof(not_pod_struct)
not_pod_struct
s.
Comments
Post a Comment