-4

我收到这里提到的错误: 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(generic) 的元素的向量 - 所以我不能将向量设为 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);
}
/* ------------ */
4

2 回答 2

3

您正在尝试调用一个带有临时引用的函数。临时只能绑定到对 const 的引用。此外,明智的做法是显示错误的实际来源。

于 2012-06-15T14:30:59.467 回答
0

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

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

愚蠢的问题,但是您是否保存了文件?还是这个错误来自代码的不同部分?

于 2012-06-15T14:35:56.617 回答