I am having problem when trying to overload the <<
operator of a template class, where I receive the error LNK2019: unresolved external symbol
error. The code is as follows:
template <class T>
struct subvec {
T vec[NDIMS];
...
friend std::ostream& operator<<(std::ostream&, const subvec<T>&);
};
...
template <class T>
std::ostream& operator<<(std::ostream& output, const subvec<T>& s) {
...
return output;
}
...
template subvec<int>;
...
int main() {
subvec<int> S(0);
cout << S;
return;
}
All the codes are in the same .cpp file. It compiles fine, but seem to have a linking problem with the cout<<S
line. If I comment it out, everything else is fine.
I have searched a few other posts regarding similar problems, but did not find an answer. The only way I can make it work is to copy the definition of operator<<
into the definition of the struct subvec<T>
instead of putting it outside. But my definition of operator<<
is still in the same file. How should I resolve this? I eventually have to separate out a header file anyway. Thanks!