简体   繁体   中英

Streaming string literals in C++

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?

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);
}

How about

template<std::size_t Size>
Printer& operator << (const char (&s)[Size]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM