I've got the following BinaryTree
class that includes a private class called Node
(I've omitted everything except what's needed for this question):
template<typename T>
class BinaryTree{
private:
template<typename NT>
class Node{
public:
Node<NT>* left;
Node<NT>* right;
NT item;
};
public:
Node<T> Find(T itemToFind);
};
which is fairly standard. I'm trying to implement the Node FindMax()
function that returns a Node
object and I'm unable to figure out how to define it. For example, I assumed (incorrectly) that this would suffice:
template<typename T>
Node<T> BinaryTree<T>::Find(T itemToFind){ // -------> error line
//...do something....
}
but I get an error saying: No template named Node
. I've tried various other combinations to no avail. I'm not looking to return a bool
if found, I want to return the Node
itself.
You need to add scope operator ::
since the Node
class is part of the BinaryTree
class:
template<typename T>
BinaryTree<T>::Node<T> BinaryTree<T>::Find(T itemToFind) {
//...do something....
}
C++14 introduced auto
return type so the following will work too:
template<typename T>
auto BinaryTree<T>::Find(T itemToFind) {
//...do something....
}
At that point, the Node
class is not in scope. You need to do something like this:
template<typename T>
BinaryTree<T>::Node<T> BinaryTree<T>::Find(T itemToFind) {
//...do something....
}
This was one of the motivations for C++11's trailing return types, which allow you to shorten the return type. IIRC, the trailing return type for member functions is evaluated within the scope of the class.
template<typename T>
BinaryTree<T>::Find(T itemToFind) -> Node<T> {
//...do something....
}
By the way, do you really want the Node class to have a template parameter that is independent of the template parameter for BinaryTree
? That is, you may want to eliminate the second template parameter NT
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.