在函数中使用模板模板参数时没有匹配函数错误

no matching function error using template template parameters in a function

本文关键字:函数 错误 参数      更新时间:2023-10-16

我正在尝试使用模板模板参数定义一个函数(我只想知道它是如何工作的)。我有以下几点:

template <typename T, template <typename> class Cont>
typename Cont<T>::iterator binary_search (typename Cont<T>::iterator first, typename Cont<T>::iterator last)
{
    typename Cont<T>::iterator it;
    // ...
    return it;
}

然后在main ()函数中:

std::vector<int> data;
// ....
std::vector<int>::iterator it = binary_search (data.begin (),data.end ());

尝试编译代码时出现此错误:

binary_search.cpp: In function ‘int main(int, char**)’:
binary_search.cpp:43:83: error: no matching function for call to ‘binary_search(std::vector<int>::iterator, std::vector<int>::iterator)’

找不到任何适当的响应来帮助我解决此错误。任何帮助将不胜感激。

提前致谢

您拥有的是非推导上下文,以及模板模板参数不匹配,即使上下文是可推导的。 std::vector采用第二个模板参数,即分配器,该参数默认为 std::allocator

对于非推导上下文,T永远无法推导,并且始终必须指定,typename表明了这一点。有关血腥的细节,请参阅此问题。