閑古鳥

オールドプログラマの日記。プログラミングとか病気(透析)の話とか。

F#の Pipeline operator もどきをC++で実装してみた

>演算子をオーバーロードして、F#の Pipeline operator のようなことをやってみました。

#include <iostream>
#include <boost/function.hpp>
using namespace std;

int one() { return 1; }
int two() { return 2; }

void print_func(int n)
{
  cout << n << endl;
}
struct print_obj {
  void operator()(int n) {
      cout << n << endl;
  }
};

void operator > (int r, boost::function<void(int)> f)
{
  f(r);
}


int _tmain(int argc, _TCHAR* argv[])
{
  // 普通の関数を使うにはキャストしてやらないと駄目……
  one() > boost::function<void(int)>(print_func);
  two() > boost::function<void(int)>(print_func);

  one() > print_obj();
  two() > print_obj();

  return 0;
}

とりあえず型を決め打ちでやってみましたが、それらしい動きをしてくれるようです。もっと自然に書けるようになると面白いかもしれませんね。