However I am currently getting this error when I try to run the program: symbol not found
I guess by "running" you mean compiling, because this is a compiler error, not a runtime error.
The problem is propbably that you defined your operator<<
in a .cpp
file, so that it is not visible to the compiler. With normal classes and functions, that's ok, but with templates it is not, as the compiler needs to see the template definition whe you intantiate the template.
The solution would be to put the operator definition in the header that defines the Hash_Table
class template. You will probably run into similar errors regarding the member functions of Hash_Table
.
Another problem is, as noted by Yuushi, the templated operator declared a friend of the class. It's a matter of taste, but I usually refrain completely from declaring friend functions if there is another solution, and there is:
template <typename T, typename K>
class Hash_Table {
//....
void printToStream(std::ostream& os) const {
//your output algorithm here
}
};
template <class T, class K>
std::ostream& operator<<(std::ostream& os Hash_Table<T,K> const& ht) {
ht.printToStream(os);
return os;
}
It's normally considered bad design to declare friends, because it partly breaks encapsulation and is an even tighter coupling than inheritance. While it's mostly a matter of taste when friends' convenience surpasses the tight coupling for normal functions, it is a huge encapsulation issue when dealing with templates, because anyone can specialize the template:
template <> istream& operator>> <int, std::string> (istream& in, const Hash_Table<int,std::string>& right)
{
right.hashTable.resize(1);
for (unsigned i = 0; i < 2000000; ++i)
right.hashTable[0].push_back("I just hijacked your Hash_Table implementation!";
}
This is evil but legal - you made that function your friend, although it might not be so friendly ;-)