C ++模板错误:没有匹配的调用函数

时间:2012-06-15 14:28:03

标签: c++ templates vector

我收到此处提到的错误: C++ Templates Error: no matching function for call std::vector<int, std::allocator<int> >

这是错误(再次):

main.cpp: In function ‘int main()’:
main.cpp:21:21: error: no matching function for call to ‘Test<int>::foo(std::vector<int, std::allocator<int> >)’
main.cpp:21:21: note: candidate is:
main.cpp:14:6: note: void Test<T>::foo(std::vector<T>&) [with T = int]
main.cpp:14:6: note:   no known conversion for argument 1 from ‘std::vector<int, std::allocator<int> >’ to ‘std::vector<int, std::allocator<int> >&’

问题是我有一个更复杂的情况,我不知道如何解决它(没有破坏太多的代码)。 我有一个通用的二进制搜索树类。我想用二进制搜索树节点中的所有值填充T(泛型)类型的元素向量 - 所以我不能使向量const。遍历树的函数是递归的。

所以我有:

/*main*/

BST<int> t;

t.add(21);
t.add(12);
//.... etc.

vector<int> elements;

t.inorder(elements);
/* ------------ */

/*BST.h*/
template<typename T>
class BST{
    //....
    Node<T>* root;
    //....
    void inorder_rec(Node<T>* root, vector<T>& result);
    void inorder(vector<T>& result);
    //....
};

template<typename T>
void BST<T>::inorder_rec(Node<T>* root, vector<T>& result){
    // recursive call for the child nodes
}

void BST<T>::inorder(vector<T>& result){
    inorder_rec(this->root, result);
}
/* ------------ */

2 个答案:

答案 0 :(得分:3)

您正在尝试调用带有临时引用的函数。临时只能绑定到const的引用。此外,显示错误实际上来自哪里是明智的。

答案 1 :(得分:0)

这是您的实际代码吗? inorder和inorder_rec的定义需要有返回类型。否则,这部分代码看起来很好,暂时看不到:

vector<int> elements;
t.inorder(elements);

愚蠢的问题,但你保存了文件吗?或者这个错误来自代码的不同部分?

相关问题