How overload resolution works for std :: vector <int> :: insert

These are two of the three method signatures insertfrom std :: vector:

void insert (iterator position, size_type n, const value_type& val);
template <class InputIterator>
void insert (iterator position, InputIterator first, InputIterator last);

Now, given the vector and insert call,

std::vector<int> v;
v.insert( v.begin(), 3, 3 );

how did it happen that the first one was chosen insert, and not the second?

I - naively, I'm sure, implemented the same signatures, but here the second (template) form was chosen by the compiler.

template <class T, int MAXSIZE>
class svector {
public:
  class iterator : public std::iterator<std::input_iterator_tag,T> { ... };

    // ...

  void insert (class iterator position, size_t n, const T& val){
    if( len + n > MAXSIZE ) throw std::out_of_range( "insert exceeds MAXSIZE" );
    uint32_t iPos = position - begin();
    uint32_t movlen = len - iPos + 1;
    for( uint32_t i = 0; i < movlen; i++ ){
      ele[len + n - i] = ele[len - i];
    }
    for( uint32_t i = 0; i < n; i++ ){
      ele[iPos + i] = val;
    }
    len += n;
  }

  template <class InputIterator>
  void insert (class iterator position, InputIterator first, InputIterator last){
    for( InputIterator it = first; it != last; it++ ){
      if( len + 1 > MAXSIZE ) throw std::out_of_range( "insert exceeds MAXSIZE" );
      *position = *reinterpret_cast<T*>( it );
    }
  }
+3
source share
1 answer

Your reading and compiler are completely correct.

The standard library implementation should take precautions (through std::enable_ifor more commonly through SFINAE ) to ensure that only the second overload is selected for iterator types.

+5
source

All Articles