【发布时间】:2016-09-30 06:04:14
【问题描述】:
假设我们有下面的向量类,它已经被缩短到最小来展示问题。
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;
// not sure if this is the beast way to check if my T is really a unique_ptr
template<typename Q = T>
typename Q::element_type* operator[](const size_t _Pos) const { return at(_Pos).get(); }
};
有什么方法可以检查 T 是否为 unique_ptr,如果是则添加 operator[] 以返回 unique_ptr::element_type*。同时,虽然普通的 operator[] 也应该可以工作。
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;
有什么方法可以实现这样的目标吗?
已编辑:
我要求这个的原因是因为我可以说我的容器
class MyVec: public VectorT<std::unique_ptr<SomeClass>>
但我也可以有一个
class MyVecView: public VectorT<SomeClass*>
这两个类的功能几乎相同。所以我试图通过做类似的事情来避免重复
template<typename T>
void doSomething(VectorT<T>& vec)
{
SomeClass* tmp = nullptr;
for (size_t i = 0; i < vec.size(); ++i)
{
tmp = vec[i]; // this has to work though
....
}
}
那我当然可以
MyVec::doSomething(){doSomething(*this);}
MyVecView::doSomething(){doSomething(*this);}
这当然意味着operator[] 必须适用于这两种情况
【问题讨论】:
-
int *p1 = uptr_v[0].get();也许? -
@MatsPetersson 编辑了我的答案,解释了我的最终目标以及为什么这不是真正的解决方案
-
@slawekwin 我只想让 operator[] 过载。 SFINAE 部分工作正常,但
using operator[]和我写的那个部分表现不佳。我缺少一些东西,我认为专业化在这种情况下不会有帮助。
标签: c++ templates c++11 sfinae