17
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

std::cout 乗っ取り計画

Posted at

某所で話題に上っていた記事より:

#include <stdio.h>
int main() {
  printf("Hello World\n");
  return 0;
}

C言語だと、!を表現するのに『\n』を使います。

いいえ、使いません。

...でもC++なら?

https://wandbox.org/permlink/k7Ixa2G9UzGeKlRd

prog.cc
# include <iostream>
int main()
{
  std::cout << "Hello World\n";
}
// 出力: Hello World!

そうそう、下記コードも忘れずにコンパイル&リンクしてね😜

magic.cc
# include <iostream>
auto magic = []{
  struct custom_streambuf : std::streambuf {
    std::streambuf& sb_;
    custom_streambuf(std::streambuf& sb)
      : sb_(sb) { setp(0, 0); }
    virtual int overflow(int ch) override
      { return sb_.sputc((ch != '\n') ? ch : '!'); }
  };
  return std::cout.rdbuf(new custom_streambuf(*std::cout.rdbuf()));
}();

より実用的(!?)なサンプルと動作原理解説は、別サイト記事「FizzBuzz化ストリーム」を参照のこと。

17
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?