1
votes

I've written a generic tree in c++, and one of my tasks is creating a tree of trees. Inorder to do so i need to create an operator between trees. lets say i can get all the comparison info i know from the info in the root. i created these template operator overloading.

template <class T>
class tree {
tree_node<T>* root;
tree_node<T> *largest;

public:
void roll(tree_node<T>* node);

tree();
~tree();
tree_node<T>* get_root();
void set_root(tree_node<T>*);
tree_node<T>* get_largest();
tree_node<T>* most_right(tree_node<T>* node);
void update_largest(tree_node<T>* node);
void update_largest_end(tree_node<T>* node);
tree_node<T>* find(T& data);
bool insert(T& data);
void del(tree_node<T>* node);
bool del(T& data);
void reverse_inorder(list<T>& list);
void partial_reverse_inorder(list<T>& list,int num);
friend bool operator<(const tree<T>& tree1,const tree<T>& tree2);
friend bool operator==(const tree<T>& tree1,const tree<T>& tree2);
};

template<class T>

bool operator<(const tree<T>& tree1,const tree<T>& tree2){

    return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator

}

template <class T>

bool operator==(const tree<T>& tree1,const tree<T>& tree2){

    return tree1.get_root()->data==tree2.get_root()->data; //assuming == operator
}

but when i try to compile it i get these error messeges:

E:\technion\mivnei\hw1\tree.h:75:68: warning: friend declaration 'bool operator<(const tree&, const tree&)' declares a non-template function [-Wnon-template-friend] friend bool operator<(const tree& tree1,const tree& tree2);

E:\technion\mivnei\hw1\tree.h:75:68: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)

E:\technion\mivnei\hw1\tree.h:76:69: warning: friend declaration 'bool operator==(const tree&, const tree&)' declares a non-template function [-Wnon-template-friend] friend bool operator==(const tree& tree1,const tree& tree2);

Does anyone know whats wrong or how to fix it? (this is not a question about the correctness of the code but just about the syntax that is required inorder to overload the operators)

1

1 Answers

1
votes

You either need to define the non-template function in the class

template <class T>
class tree {
    // ...
    friend bool operator<(const tree<T>& tree1,const tree<T>& tree2){
        return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator
    }
};

or declare the friend function template:

template <class T> class tree;

template <class T> bool operator<(const tree<T>& tree1,const tree<T>& tree2);

template <class T>
class tree {
    // ...
    // Declare specialization friend
    friend bool operator< <T>(const tree<T>& tree1,const tree<T>& tree2);
};

template <class T> bool operator<(const tree<T>& tree1,const tree<T>& tree2)
{
    return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator
}