fork download
  1. #include <deque>
  2. #include <list>
  3.  
  4. // デフォルトコンストラクタが無い
  5. class A {
  6. public:
  7. A(int n) : n(n) {}
  8. private:
  9. int n;
  10. A();
  11. };
  12.  
  13. template <class T, class Container = std::deque<T> >
  14. class stack {
  15. public:
  16. void push() { rep.push_back(T()); }
  17. void push(const T& v) { rep.push_back(v); }
  18. T top() { rep.back(); }
  19. void pop() { rep.pop_back(); }
  20. private:
  21. Container rep;
  22. };
  23.  
  24. int main(void) {
  25. stack<A> s1;
  26. stack<int> s2;
  27. stack<A*> s3; // ポリモーフィックな型でもOK
  28. stack<int, std::list<int> > s4; // 図6.9相当の実装に置換
  29.  
  30. // デフォルトコンストラクタを必要とするメソッドを呼ばない限りはOK
  31. //s1.push(); // error!
  32. s1.push(A(1));
  33. s1.top();
  34. s1.pop();
  35.  
  36. s2.push();
  37. s2.push(2);
  38. s2.top();
  39. s2.pop();
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
Standard output is empty