std::forward_listのsizeとか


Policyを使って単純に実装するとこうなるのか.


# そもそも直交してるのか?



#include <iostream>
#include <list>


template<
  typename NumericT
>
class size_counter { // サイズをカウントするポリシークラス
  NumericT size_;

protected:
  void increment(){
    ++size_;
  }
  void decrement(){
    --size_;
  }

public:
  size_counter(): size_(0){
  }
  NumericT size() const{
    return size_;
  }
};


template<
  typename NumericT
>
class non_size_counter { // サイズをカウントしないポリシークラス
protected:
  void increment(){}
  void decrement(){}
public:
  non_size_counter(){}
};


// std::forward_listのシンプル版
// std::forward_listにpush_backはないけど

template<
  typename ValueT,
  class SizeCounter = non_size_counter<std::size_t>
>
class forward_list : public SizeCounter {
  typedef ValueT value_type;

  std::list<value_type> data_;

public:
  void push_back(const value_type& value){
    data_.push_back(value);
    SizeCounter::increment();
  }

  void pop_back(){
    data_.pop_back();
    SizeCounter::decrement();
  }
};


int main(){

  template<
    template<
      typename
    >
    class SizeCounter
  >
  using int_list = forward_list<int, SizeCounter<std::size_t> >;


  // sizeがある
  int_list<size_counter> have_size;

  // sizeがない
  int_list<non_siz_counter> not_have_size;

  std::cout << have_size.size() << std::endl; // OK

  std::cout << not_have_size.size() << std::endl; // コンパイルエラー

}


でもSTLで実装しようとすると当然こんな単純にいくはずはないです.

ゼロオーバーヘッドって保障できないですしね.

これじゃ正直要らないですねぇ.