我正在做一个 POC 实现,根据要求,我需要扩展 std::vector
insert API,它只需要一个参数(要插入的值),并且代码会在内部添加这个容器的末端。
我创建了一个派生自 std::vector
的自定义类 (ValVector),并定义了一个接受单个参数但在编译时接受的自定义 Insert 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]
最佳答案
要解决您的实际问题:在类中声明一个函数会隐藏该类中所有继承的同名函数。换句话说,因为 ValVector
有一个名为 insert
的函数,继承的 std::vector::insert
在其中不再可见。解决这个问题的最好方法可能是使用 using
声明将继承的 insert
带回作用域:
template<class T, class Allocator = allocator<T>>
class ValVector : public std::vector<T, Allocator> {
public:
using std::vector<T, Allocator>::insert;
BOOL insert(const T& elem) { return (this->insert(this->end(),elem)!=this->end()); }
};
但是,我要发表评论。我认为你的做法是错误的。 std
容器不适用于公共(public)继承;如果不出意外,它们没有虚拟析构函数,也没有 protected 成员。您最好提供一个免费函数,然后可以将其用于任何 std::vector
,而不仅仅是您的类型:
template <class T, class A>
BOOL insert(std::vector<T, A> &vec, const T &val)
{
return vec.insert(vec.end(), val) != vec.end();
}
或者使其更通用一些以适用于任何容器:
temlate <class C, class E>
BOOL insert(C &cont, const E &val)
{
return cont.insert(cont.end(), val) != cont.end();
}
关于c++ - 无法重载现有的 std::vector 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31291824/