Sam*_*rsa 17 c++ templates overloading
考虑以下std :: vector的声明(取自cplusplus - EASTL具有相同的声明)
iterator insert ( iterator position, const T& x );
void insert ( iterator position, size_type n, const T& x );
template <class InputIterator>
void insert ( iterator position, InputIterator first, InputIterator last );
Run Code Online (Sandbox Code Playgroud)
如果我输入
someVector.insert(someVector.begin(), 10, 90);
Run Code Online (Sandbox Code Playgroud)
如何是,不与最后过载混淆(由编译器),其中,10和90是intS和InputIterator的类型被取为int这是采取替代,而不是10作为size_type与20作为一个const int&?
现在我说"不"因为我正在实现一个向量容器(学习目的),在我的情况下使用上面提到的调用,第三个重载是由编译器而不是第二个重载选择的,因此无法编译.如果我删除第三个过载,那么事情看起来很好.
它是否与最后一个重载调用的内容有关(带迭代器特征的重载函数)?如果是这样,那么如果我认为所有的迭代器是原始指针(虽然在我的情况下,我使用了相同的声明,这意味着我有超载#3与期望的迭代器......虽然预计是错误的模板这里说的是因为最后它可以是任何东西,在这种情况下,它被解释int为我并且无法编译)我将如何确保编译器选择正确的函数?
Ker*_* SB 12
出于好奇,我看了一下海湾合作委员会的消息来源:
template<typename _InputIterator>
void
insert(iterator __position, _InputIterator __first,
_InputIterator __last)
{
// Check whether it's an integral type. If so, it's not an iterator.
typedef typename std::__is_integer<_InputIterator>::__type _Integral;
_M_insert_dispatch(__position, __first, __last, _Integral());
}
Run Code Online (Sandbox Code Playgroud)
后来...
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 438. Ambiguity in the "do the right thing" clause
template<typename _Integer>
void
_M_insert_dispatch(iterator __pos, _Integer __n, _Integer __val,
__true_type)
{ _M_fill_insert(__pos, __n, __val); }
// Called by the range insert to implement [23.1.1]/9
template<typename _InputIterator>
void
_M_insert_dispatch(iterator __pos, _InputIterator __first,
_InputIterator __last, __false_type)
{
typedef typename std::iterator_traits<_InputIterator>::
iterator_category _IterCategory;
_M_range_insert(__pos, __first, __last, _IterCategory());
}
Run Code Online (Sandbox Code Playgroud)
看起来他们确实担心会出现歧义,所以明确使用typetraits和overloading来检查模板是否匹配整数类型.