简体   繁体   中英

Unexpected error when creating a friend template function

guys I am trying to create a template for my class SortedList. I want to overload the << operator, so I declare a friend function inside the class but every time I try to compile the main.cpp I get the following error: template-id 'operator<< ... ' does not match any template declaration. here you the code from main.cpp

int main()
{
    SortedList<int, int> lst, lst2;
    int a = 2;
    lst.addItem(2, 3);
    cout << lst << endl;
    return 0;
}

this is the template class declaration and definition

template <typename K, typename V>
struct Node
{
    K key;
    V value;
    Node<K, V>* next;
};
template <typename K, typename V>
class SortedList
{
friend ostream& operator << <K, V>(ostream&, const SortedList&);
public:

    SortedList();
    SortedList(const SortedList&);
    SortedList& operator = (const SortedList&);
    ~SortedList();

    void addItem(const K&, const V&);
    void removeElem(const K&);
    void removeAt(int);
    bool remove(const K&);


private:

    Node<K, V>* start;
    size_t n;

};

Well you can find a good explanation on C++ faq perhaps I'll quote it:

The snag happens when the compiler sees the friend lines way up in the class definition proper. At that moment it does not yet know the friend functions are themselves templates.

When you call the operator+ or operator<< functions, this assumption causes the compiler to generate a call to the non-template functions, but the linker will give you an "undefined external" error because you never actually defined those non-template functions.

One solution is to put:

template<typename K, typename V> class SortedList;
template<typename K, typename V> std::ostream& operator<< (std::ostream& o, const SortedList<K,V>& x);

On top, Here is an example for you class (that compiles perfectly, just does nothing).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM