根据模板参数删除成员

时间:2015-02-01 16:53:43

标签: c++ templates vector

我想设计一个带有小矢量优化的矢量类。它看起来像:

template <typename T, int small_size = 0>
class Vector {
private:
    T data_small_[small_size];
    T* data_;
    T* size_;
    T* capacity_;
public:
    ...
}

不幸的是,大多数情况下,该类将与small_size = 0一起使用。有没有办法删除data_small_ for small_size = 0而不进入模板专门化并重写该类的整个代码?

1 个答案:

答案 0 :(得分:5)

您可以在此处使用empty base optimization。您必须将Vector更改为不直接引用data_small_。相反,编写使用SmallData来实现所需的成员函数并处理部分特化small_size = 0中的SmallData<T, 0>个案。以下是SmallData实施复制构造函数的示例,operator[]Vector使用它们而不必担心small_size

template <typename T, int small_size>
class SmallData
{
 public:
  SmallData(const SmallData& other)
  {
   for(size_t i = 0; i < small_size; i++)
     data_small_[i] = other.data_small_[i];
  }

 T& operator[](int k){return data_small_[k];} 
 protected:
  T data_small_[small_size];
};

template <typename T>
class SmallData<T, 0>
{
 public:
 T& operator[](int k){//throw some error} 
};

template <typename T, int small_size = 0>
class Vector : public SmallData<T, small_size>
{
 public:
 Vector(const Vector& other) : SmallData<T, small_size>(other)
 {
  //rest of copy ctor either here on in the member init list above
 }
 T& operator[](int k)
 {
  if(k<small_size) return SmallData<T, small_size>::operator[](k);
  else return data_[k];
 }
};