简体   繁体   中英

How does overload resolution work for std::vector<int>::insert

These are two out of three insert method signatures from 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 a vector and an insert call,

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

how come that the 1st insert is chosen and not the second one?

I have - naively, I'm sure - implemented the same signatures, but here the second (templated) 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 );
    }
  }

Your reading, and the compiler, are entirely correct.

The standard library implementation has to take precautions (via std::enable_if or more generally via SFINAE ) to ensure that the second overload is chosen only for iterator types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM