Stream input operators


#1

Sorry if this was already discussed in the past, but I could not find any reference in the forum.

What is the reason not to define input stream operators in Juce? There are output stream operators, such as OutputStream::operator<<() but no InputStream::operator>>(). The same holds for String.

They can be very useful when some genericity is involved, e.g. when trying to input/output containers.

I would like to write something like:

template <class DataType>
OutputStream& operator<<(OutputStream& output, const Array<DataType>& array)
{
  output << (int)array.size();
  for (int i = 0; i != size; ++i)
     output << array[i];
  return output;
}

template <class DataType>
InputStream& operator>>(InputStream& input, Array<DataType>& array)
{
  int size;
  input >> size;
  array.clearQuick();
  array.ensureStorageAllocated(size);
  for (int i = 0; i != size; ++i)
  {
     assert(!input.isExhausted());
     DataType value;
     input >> value;
     array[i].add(value);
  }
  return input;
}

Since no operator>> are defined for builtin types, the second part does not work, even with Array. Of course, I could overload operator>> for builtins externally (delegating to readInt(), etc.), but I’m pretty sure there was a motivation for not encouraging things like this :slight_smile:

No?


#2

There’s no reason not to have them, I guess I just never tend to use the >> operator myself, and never got round to adding it… I’ll put it on my list of small “tinkering around” things to do.


#3

Ok, no problem, I can live without them.

Actually there is a semantic issue here, I was expecting OutputStream and InputStream to be always binary-oriented, but operator<< actually interprets data to output it as a String (like c++ standard library does with fstream).

So in any case, these operators would not provide a generic way to output binary data, in the Array example in my first post, everything would be output as Ascii…

Thus for the moment my solution is to define overloaded external functions write_binary(outputstream&, const value_type&) and read_binary(inputstream&, value_type&).

It could be nice to have a more generic solution to high level serialization in Juce, but I guess there are many more important things to do :slight_smile:


#4