我收到这里提到的错误: 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);
}
/* ------------ */