Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming string literals in C++

Tags:

c++

stl

literals

Let's say that I have some in-house framework for files and streams. I have IOutputStream interface class with write(char const *buffer, size_t size) and flush(). I have a tool, called Printer which can be used with any instance of IOutputStream descendants. Then I have Printer & operator<<(T x) style methods, where T x is the data (or a reference or a pointer to it) to be written.

For example Printer & operator<<(int x) will translate x to string, and will call the referenced output stream's write(...) function for real.

Let's see the problem! Invocation: printer << "appletree";. It calls Printer & operator<<(char const *s). For this kind of usage, I have to call an strlen(s) to determine the size, and after that I can call the final step. This is rather insane since I know the length of appletree at compile time.

Are there any good practice for this? How STL's ostream plays with titerals?

like image 666
Notinlist Avatar asked Jan 28 '26 23:01

Notinlist


1 Answers

Since string literals have type const char(&)[], you could add an overload for them:

template<size_t n>
Printer& operator<<(const char (&cstring)[n]) {
    write(cstring, n - 1);
}
like image 192
mfontanini Avatar answered Jan 30 '26 17:01

mfontanini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!