【发布时间】:2017-07-14 04:43:58
【问题描述】:
我在类似 STL 的列表容器中定义了以下两个函数:
// copy the specified VALUE some COUNT number of times and insert copies
// right before POS.
Iterator insert(Iterator pos, size_type count, const value_type
&value);
// copy the values from [FIRST, LAST) from the specified Iterators and
// place before POS.
template<class InputIt>
Iterator insert(Iterator pos, InputIt first, InputIt last);
然后我尝试用一些任意代码测试我的函数实现:
std::list<int> stlList = { 1, 2, 3, 4, 5 };
MyList<int> intList;
intList.insert(intList.begin(), 5, 0); // expected call to first insert
intList.insert(intList.begin(), stlList.begin(), stlList.end()); // expected call to second insert
但是,对于他们俩来说,似乎正在调用第二个函数。我有点模棱两可,因为这两个函数都有三个参数,所以我看到编译器可能会调用错误的函数。但我不确定我错过了什么。我的函数基于 STL,据我所知,它们以几乎相同的方式定义它们 (STL's List Insert)。
【问题讨论】:
-
size_type定义为什么? -
我认为你的
size_type是无符号的,所以模板方法是完全匹配的。您可以拨打intList.insert(intList.begin(), 5u, 0) -
注意关于
std::list::insert的重载(4)(有两个迭代器的那个)的注释:“这个重载只有在InputIt符合InputIterator时才参与重载决议,以避免歧义与重载 (3)。" -
你必须使用 SFINAE。
-
@ThomasPaine 一种方法是使用
std::enable_if。您需要编写一个 type_trait 来检查一个类型是否是一个迭代器(它应该具有iterator_traits的特化)。见this question。