元ネタはクロージャによるクラスの代替 – Inside Closure – nihmaの日記です。それC++でもできるよ!というわけでやってみました。Visual C++ 2010 β2で試しました。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <memory>
#include <functional>
#include <vector>
#include <iostream>
 
template<typename T>
struct Stack
{
  std::function<void (T)> push;
  std::function<T ()> pop;
 
  static Stack create()
  {
    auto arr = std::make_shared<std::vector<T>>();
    Stack s;
    s.push = [arr](T n) {
      arr->push_back(std::move(n));
    };
    s.pop = [arr]() -> T {
      auto ret = std::move(arr->back());
      arr->pop_back();
      return ret;
    };
    return s;
  }
};
 
int main()
{
  using std::cout;
  using std::endl;
  auto a = Stack<int>::create();
  auto b = Stack<int>::create();
 
  a.push(0); b.push(5);
  a.push(1); b.push(6);
  a.push(2); b.push(7);
  a.push(3); b.push(8);
  a.push(4); b.push(9);
 
  cout << "a:" << a.pop() << " b:" << b.pop() << endl; // a:4 b:9
  cout << "a:" << a.pop() << " b:" << b.pop() << endl; // a:3 b:8
  cout << "a:" << a.pop() << " b:" << b.pop() << endl; // a:2 b:7
  cout << "a:" << a.pop() << " b:" << b.pop() << endl; // a:1 b:6
  cout << "a:" << a.pop() << " b:" << b.pop() << endl; // a:0 b:5
}

ちなみに、ABだとラムダ(無名関数)がないのが厳しいですが、デリゲートがあるのでやはりやってやれないことはないという結論になります。


スポンサード リンク

この記事のカテゴリ

  • ⇒ クロージャでクラスる