This question already has an answer here:
I have two conflicting function overload for insert in my own implementation of std::vector.
namespace PR {
template <typename T>
class vector {
...
// First insert function takes a value and inserts count copies at pos
iterator insert(const_iterator pos, size_t count, const T& value);
// Second insert function takes an iterator for the first and last element and inserts
// it at pos.
template <typename input_iterator>
iterator insert(const_iterator pos, input_iterator first,
input_iterator last);
...
}
Now if I do a function call like this:
auto iter = vec1.insert(vec1.cbegin() + 1, 1, 4);
I get an error message like this:
/home/panky92/C++/ImplVector/./Vector.h:395:14: required from ‘T* PR::vector<T>::insert(PR::vector<T>::const_iterator, input_iterator, input_iterator) [with input_iterator = int; T = int; PR::vector<T>::iterator = int*; PR::vector<T>::const_iterator = const int*]’
/home/panky92/C++/ImplVector/test/tests-main.cpp:211:57: required from here
/usr/include/c++/7/bits/stl_algobase.h:377:57: error: no type named ‘value_type’ in ‘struct std::iterator_traits<int>’
typedef typename iterator_traits<_II>::value_type _ValueTypeI;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:379:64: error: no type named ‘iterator_category’ in ‘struct std::iterator_traits<int>’
typedef typename iterator_traits<_II>::iterator_category _Category;
It looks like it is calling the second insert function with iterator input instead of the first one, even though my intention was to call the first one with this function call. This function call worked before I included the second overload function.
The calls below are working as expected:
PR::vector<std::string> strvec{"Hello", "World", "!!"};
auto iter = strvec.insert(strvec.cbegin() + 1, 2, "C++"); // calls the first insert function
PR::vector<int> vec1{1, 2, 3};
PR::vector<int> vec2{1, 2, 3};
auto iter1 = vec1.insert(vec1.cbegin() + 1, vec2.begin(), vec2.end()); // calls the second insert function
Can someone explain what I am doing wrong here?
Aucun commentaire:
Enregistrer un commentaire