0

How do I implement my own custom stream in C++?

Why?

I want to send data from one micro-controller to another using a wired connection and I think a custom stream is the most intuitive way.

Example:

#include "myStream.h" int main() { myStream << "Hello world!"; return 0; } 

EDIT:

Solution:

class Stream { private: // members public: Stream() {} friend Stream& operator<<(Stream& stream, const Whatever& other); }; Stream& operator<<(Stream& stream, const Whatever& other) { // do something return stream; } 
8
  • 1
    It's just operator overloading. Commented Mar 19, 2021 at 17:46
  • If you want it to be std-compatible (to allow tricks like endl), start here: stackoverflow.com/questions/772355/… Commented Mar 19, 2021 at 17:55
  • @szatmary It's actually not, not if you want to use all the existing operator<< overloads that work for ostream and ofstream and ostringstream. Commented Mar 19, 2021 at 18:32
  • 1
    What is a "Wired connection"? Is it a lan wire, is it a usb wire, is it pio wiring? Commented Mar 19, 2021 at 19:13
  • 1
    @Ivanovic "one microcontroller to another" probably means SPI/I2C Commented Mar 19, 2021 at 23:19

1 Answer 1

2

If you look at how streams work, it's just a case of overloading operator<< for both your stream object, and the various things you want to send to it. There's nothing special about <<, it just reads nicely, but you could use + or whatever else you want.

Sign up to request clarification or add additional context in comments.

4 Comments

When I try to overload operator<<, I get the error error: invalid operands of types ‘Stream()’ and ‘int’ to binary ‘operator<<’
It's worth opening up a new question with code that can reproduce that problem. You will likely need to have a few other questions answered before you've wrapped this up.
@tadman Actually your idea does not allow all of the standard library's existing stream functionality to work. It is possible to make your own stream that automagically works like ofstream/ostringstream/etc, so you can write ints to it as decimal, set formatting options, etc.
@user253751 You can make your own entirely independent "stream" system, or you can leverage the existing one and make a stream-compatible one. Both approaches have their utility. I interpreted "custom stream" as not compatible, but independent.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.