jeudi 29 septembre 2016

Add operator[] for vector when Type is unique_ptr

Suppose that we have the vector class below which has been shortened to minimum to showcase the question.

template <typename T>
class VectorT : private std::vector<T>
{
  using vec = std::vector<T>;
public:
  using vec::operator[];
  using vec::push_back;
  using vec::at;
  using vec::emplace_back;

  template<typename Q = T>
  typename Q::element_type* operator[](const size_t _Pos) const { return at(_Pos).get(); }
};

Is there any way to check if T is a unique_ptr and if yes to add an operator[] to return the unique_ptr::element_type*. At the same time though the normal operator[] should also work.

VectorT<std::unique_ptr<int>> uptr_v; 
uptr_v.emplace_back(make_unique<int>(1));
//int* p1 = uptr_v[0]; // works fine if using vec::operator[]; is commented out
                          then of course it wont work for the normal case
//std::cout << *p1;

VectorT<int*> v;
v.emplace_back(uptr_v[0].get());
int *p2 = v[0];
std::cout << *p2;

Any way to achieve something like that ?

Aucun commentaire:

Enregistrer un commentaire