将模板函数传递到另一个模板函数

时间:2020-12-15 16:04:01

So, I have a function, preorder processing, that's meant to execute the function f on each item in each node of a bst. The function is as follows:

所以,我有一个函数,预订处理,这意味着在bst的每个节点中的每个项目上执行函数f。功能如下:

template <class Item, class Key, class Process>
void preorder_processing(bstNode<Item, Key>*& root, Process f)
{
    if (root == NULL) return; 
    f(root);
    preorder_processing(root->left(), f); 
    preorder_processing(root->right(), f);
}

Unfortunately, when I call the class from within the main function, I get an error. The call is preorder_processing(root_ptr, print); and the actual function 'print' is:

不幸的是,当我从main函数中调用类时,我收到一个错误。调用是preorder_processing(root_ptr,print);而实际的'print'功能是:

template<class Item> 
void print(Item a) 
{
    cout << a << endl;
}

The error is:

错误是:

bstNode.cxx:23: error: no matching function for call to ‘preorder_processing(bstNode<int, long unsigned int>* <unresolved overloaded function type>)

bstNode.cxx:23:错误:没有用于调用'preorder_processing的匹配函数(bstNode * )' ,long>

Does anyone know what's going on?

有谁知道发生了什么?

1 个解决方案

#1


0  

Your root->left() and root->right() should be returning bstNode<Item, Key>* which is an rvalue pointer. You cannot assign a non-const reference to a temporary pointer variable.

你的root-> left()和root-> right()应该返回bstNode *这是一个右值指针。您不能将非const引用分配给临时指针变量。 ,key>

Change the declaration as below and the compiler error should go:

更改声明如下,编译器错误应该是:

void preorder_processing(bstNode<Item, Key>* root, Process f)
                 //    removed reference  ^^^

Moreover, the 2nd parameter Process f is not passed any value when you call the function:

而且,调用函数时,第二个参数Process f没有传递任何值:

preorder_processing(root->left(), ???); 

#1


0  

Your root->left() and root->right() should be returning bstNode<Item, Key>* which is an rvalue pointer. You cannot assign a non-const reference to a temporary pointer variable.

你的root-> left()和root-> right()应该返回bstNode *这是一个右值指针。您不能将非const引用分配给临时指针变量。 ,key>

Change the declaration as below and the compiler error should go:

更改声明如下,编译器错误应该是:

void preorder_processing(bstNode<Item, Key>* root, Process f)
                 //    removed reference  ^^^

Moreover, the 2nd parameter Process f is not passed any value when you call the function:

而且,调用函数时,第二个参数Process f没有传递任何值:

preorder_processing(root->left(), ???);