C++のiostreamの<<を導入したのはストラウストラップ
最近@karino2さんのポッドキャスト「プログラム雑談」のバックナンバーをいろいろ聴いている:
二週間ほど前に書いた聴いてるポッドキャストの記事ではまだ「気になっている」という分類だったのだけど、聴き始めたらいい感じにゆるいのと技術的な内容が面白いのと(そして本人の技術や生活に関する哲学が見えるのも)で、続けて聴いている。
2020年あたりの「ストラウストラップ本のエピソード」で:
「iostreamの<<構文を導入した人は何十年かに渡って『やっちまった』と思っているはず」という話があった。
ここら辺の:
のoperator<<
メソッドをオーバーロードしてIO出力に使う構文の話だ。確かにあの構文はC++の見た目のユニークさの最たるもので、それはつまり後続言語にまったく模倣されなかったということだ。自作言語勢でも「IOはあの構文で行こう」と考えている人は見たことがない。
ただ、「途中結果として不必要な文字列を作成することなく複数の文字列をバッファに書き込む」ということをうまく表そうと考えると、それなりに理に適った構文なような気もする。<<
をオーバーロードしている、というのはかなり怪しげではあるが・・・
で「導入した人」って誰なの?と自分も気になったので調べたところ、記事のタイトルにもあるとおりストラウストラップ本人だった。まあ意外性のない無難な結果である。
ストラウストラップのウェブサイトに載ってる、彼が2001年に中国のC++ View誌でインタビューされた記事をみると:
C++ View: Jerry Schwarz reviewed the history of IOStream in the preface of the book Standard C++ IOStream and Locales. I guess that there must be many interesting stories in the process of transiting from classic stream into the standard IOStream. Can you tell us some?
Bjarne Stroustrup: I do not want to try to add to Jerry's description of the transition from my streams to the current iostreams. Instead, I'd like to emphasize that the original streams library was a very simple and very efficient library. I designed and built it in a couple of months.
The key decisions was to separate formatting from buffering, and to use the type-safe expression syntax (relying on operators << and >>). I made these decisions after discussions with my colleague Doug McIlroy at AT&T Bell Labs. I chose << and >> after experiments showed alternatives, such as < and >, comma, and = not to work well. The type safety allowed compile-time resolution of some things that C-style libraries resolve at run-time, thus giving excellent performance.
iostreams自体はStroustrupが実装したわけではないけど<<
を使うスタイルは彼が作ったstreamsから継承されたもの、とのこと。StroustrupのA History of C++によるとstreamsは1984年に実装されたようだ。
他のオペレータのオーバーロードも試したけど<<
が一番うまくいった、ということのようだが、そもそも標準出力でオペレータを使う必要はあったのだろうか?普通のメソッドではダメなのか?というのは気になるところだ。少なくともストラウストラップは2001年の時点では(公式には)このデザインに不満を持っていたわけではなかったようだ。前述のA History of C++によると:
The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy. This requires operators that return their left−hand operand for use by further operations.
というわけでオペレータを使ったら?というアイデアはこのDoug McIlroyの提案らしい。彼が「やっちまった」と思い続けているかは定かでない。