我正在进行POC实现,并且根据要求我需要扩展std::vector插入API,它只需要单个参数(要插入的值),并且内部代码会在容器的末尾添加它.
我创建了一个自定义类(ValVector)派生自std::vector并定义了一个自定义插入API,它接受单个参数但在编译时抛出错误.
以下是带有错误消息的代码段代码:
#include <iostream>
#include <vector>
using namespace std; 
typedef bool BOOL;
template<class T, class Allocator = allocator<T>>
class ValVector : public std::vector<T, Allocator> {
  public: 
    BOOL insert(const T& elem) { return (this->insert(this->end(),elem)!=this->end()); }
 };
int main ()
{
  std::vector<int> myvector (3,100);
  std::vector<int>::iterator it;
  myvector.push_back (200 );
  ValVector<int> mKeyAr;
  mKeyAr.insert(10); // 
 std::cout << "myvector contains:";
  for (auto it=mKeyAr.begin(); it<mKeyAr.end(); it++)
    std::cout << ' ' << *it;
  std::cout << '\n';
  return 0;
}
错误信息:
In instantiation of 'BOOL ValVector<T, Allocator>::insert(const T&) [with T = int; Allocator = std::allocator<int>; BOOL = bool]': 
23:19: required from here 
11:72: error: no matching function for call to 'ValVector<int>::insert(std::vector<int>::iterator, const int&)' 
11:72: note: candidate is: 
11:10: note: BOOL ValVector<T, Allocator>::insert(const T&) [with T = int; Allocator = std::allocator<int>; BOOL = bool] 
11:10: note: candidate expects 1 argument, 2 provided In member function 'BOOL ValVector<T, Allocator>::insert(const T&) [with T = int; Allocator = std::allocator<int>; BOOL = bool]': 
11:88: warning: control reaches end of non-void function [-Wreturn-type] 
当您为非虚拟的东西创建自己的插入成员函数时,您会从更高的位置隐藏所有相同名称的函数(我认为这称为隐藏)。您现在尝试调用一个不再可见的函数。
是否有充分的理由不只创建一个单独的函数来满足您的需要,或者您是否必须从向量中派生出这个函数?您所做的任何事情都不需要访问受保护的数据或功能......
// from
vector.insert(data);
// to
insert_poc(vector, data);