被调用的模板功能错误

时间:2017-02-23 15:42:54

标签: c++ function templates

我在类似STL的列表容器中定义了以下两个函数:

const event: CustomEvent & { dataTransfer?: DataTransfer } =
    new CustomEvent(eventName, { bubbles: true, cancelable: true });

然后我尝试用一​​些任意代码测试我的函数实现:

// 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);

然而,对于他们两个,似乎第二个函数被调用。我有点看到歧义,因为两个函数都有三个参数,我看看编译器如何调用错误的函数。但我不确定我错过了什么。我一直把我的函数基于STL,据我所知,他们用几乎相同的方式定义它们(STL's List Insert)。

2 个答案:

答案 0 :(得分:2)

intList.insert(intList.begin(), 5, 0);选择

的原因
template<class InputIt>
Iterator insert(Iterator pos, InputIt first, InputIt last);

Iterator insert(Iterator pos, size_type count, const value_type &value);

是因为模板函数产生完全匹配。

50具有相同的类型,因此InputIt被推断为int,这使得函数看起来像

Iterator insert(Iterator pos, int first, int last);

你的其他重载看起来像

Iterator insert(Iterator pos, size_t first, int last);

正如您所见,无需转换即可调用模板推导版本,因此优先于非模板重载。

您必须将5强制转换为size_t以使其调用非模板重载,或者使用SFINAE仅在InputIt实际上是迭代器时调用模板重载。 / p>

答案 1 :(得分:2)

template<class InputIt>
    Iterator insert(Iterator pos, InputIt first, InputIt last);

此模板定义了第二个和第三个参数类型相同的函数。您假设第二个和第三个参数必须是迭代器。但是这里没有这样的要求,只是第二个和第三个参数的类型必须相同。模板参数“InputIt”的名称无关紧要。

intList.insert(intList.begin(), 5, 0); // expected call to first insert

此函数调用的第二个和第三个参数是相同的类型:int。重载决策的另一个候选者:

Iterator insert(Iterator pos, size_type count, const value_type 
        &value);

这个参数的第二个和第三个参数类型不同。虽然这两个int都可以在这里转换,但是另一个模板函数是更好的匹配,因此它被选中。

相关问题