c++ - 约束模板函数参数类型
问题描述
有两个插入函数,定义如下
template<typename T, typename Allocator>
auto list<T, Allocator>::insert(iterator pos, size_t count, const T & value)->iterator
{
for (size_t i = 0; i < count; i++) {
pos = insert(pos, value);
}
return pos;
}
template<typename T, typename Allocator>
template<typename InputIt>
auto list<T, Allocator>::insert(iterator pos, InputIt first, InputIt last) -> iterator
{
for (InputIt iter = first; iter != last; ++iter) {
pos = insert(pos, *iter);// Indirection operator ( * ) is applied to a nonpointer value.
}
return pos;
}
当T的类型为int时,下面调用insert会报错
list<int> l1;
l1.insert(l1.begin(),10, 2);//cause error
因为第二个插入函数可以比第一个匹配得更准确(无需转换)
有没有办法限制 InputIt 的类型?该函数只有在 InputIt 中存在某种类型时才能匹配