閑古鳥

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

C++ で delegate

でっちあげてみた。 id:wata_d:20060309:1141873430 と同じ事を C++ で。

#include 
#include 

template
class Delegater
{
  std::vector > func_;
public:
  Delegater() {}
  template
  Delegater(const U& f)
  {
      func_.push_back(f);
  }

  template
  Delegater& operator+=(const U& f)
  {
      func_.push_back(f);
      return *this;
  }

  void Invoke()
  {
    for(size_t i = 0; i < func_.size(); ++i)
    {
      (func_[i])();
    }
  }

};

こんなクラスを作っておいて……

#include 
typedef Delegater print;

void hoge_print() { std::cout << "hoge" << std::endl; }
void hige_print() { std::cout << "hige" << std::endl; }

int _tmain(int argc, _TCHAR* argv[])
{
  print d = &hoge_print;
  d += &hige_print;
  d.Invoke();

  return 0;
}

と使う。メンバ関数を登録することも boost::function は対応しているので、やってやれないことはないと思います。やりませんが。