简体   繁体   English

重载解析如何适用于std :: vector <int> :: insert

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

These are two out of three insert method signatures from std::vector: 这些是来自std :: vector的三个insert方法签名中的两个:

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? 怎么选择第一个insert而不是第二个insert

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. 标准库实现必须采取预防措施(通过std::enable_if或更一般地通过SFINAE )以确保仅为迭代器类型选择第二个重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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