1

出于一些必要的原因,我对一些标准容器进行了子类化,例如std::vector继承private

template<typename T>
struct MyVector : private std::vector<T>
{
  typedef std::vector<T> vector;

  using vector::begin;  // ok
  using vector::end;  // ok
  using vector::size;  // ok
  using vector::operator ==;  // <---- error

  // Other customized methods
};

大多数时候,using语法用于将这些方法带入子类的范围。
只有当我想做一些额外的事情时,显式重载才完成。

一切正常,除了std::vector::operator ==没有进入范围并给出编译器错误:

错误:没有匹配MyVector<int>::vector{aka std::vector<int, std::allocator<int> >}::operator==in MyVector<int>::vector {aka class std::vector<int, std::allocator<int>

我试图用自定义类来模拟这种情况,它编译得很好
使用标准容器,编译失败

通过浏览 的源代码std::vector,我可以看到operator ==类体内的存在。
operator ==纳入 范围的正确语法是MyVector什么?

4

1 回答 1

1

标准容器中的大多数运算符重载都是非成员,因此您将无法找到它们。

但是,我会注意到(根据我在标准中阅读的内容)并不一定是这种情况。然而,似乎大多数常见的实现都会这样做。如果你想使用std::vector'soperator==你可以重载它,就像它在标准中定义的那样使用你带来的东西,你可以这样做:

bool operator == (const MyVector &other) const
{
  const std::vector &this_ = *this, &other_ = other;
  return this_ == other_;
}
于 2013-07-20T06:09:20.617 回答