c++ - Not able to overload existing std::vector functions -


i doing poc implementation , per requirement need extend std::vector insert api take single parameter (value inserted) , internally code add in end of container.

i created custom class (valvector) derived std::vector , defined custom insert api accepts single parameter while compiling throws error.

appreciate quick response.

below snippet code error message:

#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:";   (auto it=mkeyar.begin(); it<mkeyar.end(); it++)     std::cout << ' ' << *it;   std::cout << '\n';    return 0; } 

error message:

in instantiation of 'bool valvector<t, allocator>::insert(const t&) [with t = int; allocator = std::allocator<int>; bool = bool]':  23:19: required here  11:72: error: no matching function call '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]  

to address actual question: declaring function in class hides inherited functions of same name in class. in other words, because valvector has function named insert, inherited std::vector::insert no longer visible in it. best way solve bring inherited insert scope using declaration:

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()); } }; 

however, have comment make. think approach wrong. std containers not intended public inheritance; if nothing else, have no virtual destructor , no protected members. you'd better off providing free function, used std::vector, not type:

template <class t, class a> bool insert(std::vector<t, a> &vec, const t &val) {   return vec.insert(vec.end(), val) != vec.end(); } 

or make bit more generic work container:

temlate <class c, class e> bool insert(c &cont, const e &val) {   return cont.insert(cont.end(), val) != cont.end(); } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -