1
votes

i have a template class, and when im runing the program it says

error LNK2019: unresolved external symbol "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class CSet &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$CSet@H@@@Z) referenced in function "public: void __thiscall Menu::menu(void)" (?menu@Menu@@QAEXXZ)

on any kind of data structure i try to use, if anyone can explain to me why the overloading of printing function makes this error i'll be happy to ear about it.

template <class T> class CSet{
T* Array;
int size;
public:
CSet()
{
    Array = NULL;
    size = 0;
}
CSet(CSet& other){
    size = other.size;
    Array = new T[size];
    for (int i = 0; i < size; i++)
        Array[i] = other.Array[i];
}
friend ostream& operator <<(ostream& out, CSet& other);
~CSet()
{
    if (size > 0)
        delete[] Array;
}
};


template <class T> ostream& operator <<(ostream& out, CSet<T>& other){
out << "(";
for (int i = 0; i < other.size; i++){
    if (size>1)
        out << other.Array[i] < ",";
    else
        out << other.Array[i];
}
out << ")" << endl;
return out;
}
1

1 Answers

3
votes

The friend declaration does not declare a function template, but a separate function for each instantiation of the class template. Therefore, the template you define is not the same as these functions, which remain undefined.

There are two options to fix this.

Either define the friend operator inside the class, rather than just declaring it there:

friend ostream& operator <<(ostream& out, CSet& other) {
     // implementation
}

Or declare the function template before the class definition:

template <class T> class CSet;
template <class T> ostream& operator <<(ostream& out, CSet<T>&);

and declare the template to be a friend:

friend ostream& operator << <T>(ostream& out, CSet&);
                            ^^^