在C++中使用typename作为函数参数时,如何传递引用?

ton*_*ian 3 c++ templates

模板有一些奇怪的问题.当试图传递参数化迭代器时,它抱怨没有找到任何函数.代码片段在这里,忘记了功能,它使用了对模板化迭代器的引用我感兴趣的是什么

#include <list>
#include <iostream>

template<typename T>
void print_list_element(typename std::list<T>::iterator& it){
    std::cout << *it << std::endl;
}

int main() {
    std::list<int> theList;
    theList.push_back(1);

    std::list<int>::iterator it = theList.begin();
    print_list_element(it);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您尝试使用g ++ v4.3.2编译它,它会抱怨说:

main.cpp:14: error: no matching function for call to 'print_list_element(std::_List_iterator<int>&)'
Run Code Online (Sandbox Code Playgroud)

我写的代码有什么问题,或者g ++需要更多信息吗?

sth*_*sth 9

g ++无法弄清楚print_list_element它应该使用哪个模板重载.如果您明确指定模板参数,它可以工作:

print_list_element<int>(it);
Run Code Online (Sandbox Code Playgroud)


Gre*_*ers 5

更好的方法是编写这样的函数:

template<typename Iter>
void print_element(Iter it){
    std::cout << *it << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这将适用于任何类型的迭代器,而不仅仅是std::list<T>::iterator.此外,将从参数中正确推导出模板类型.

我意识到这是一个人为的例子,但几乎总是你可能不想传递list<T>::iterator给函数.在最坏的情况下,至少是ListType上的模板,以便您的代码可以使用带有自定义分配器的列表.