Click here to Skip to main content
15,570,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do we properly create an overloaded operator specifically this "<<" and also with a templated parameter?

I do had an implementation of it but the problem was and for some reason the output was an address/reference of it, and my custom overloaded operator did not work?

And I stumbled upon this syntax where I have this second parameter of a declaration and which had an empty type-param. Why does the compiler did not complaint? maybe because I initialized this template see @ "What Have you Tried" and it can still be ran but for me its like a bug cause it did not work as I intended for?
std::ostream& operator<<(std::ostream& out, const HashNode</*empty*/>& node) {
    return out << "[ " << "key: " << node.getKey() << ", " << "val: " << node.getValue() << " ]";
}


What I have tried:

C++
//REM: HashNode.h
template<typename K = int, typename V = std::string>
class HashNode { ... };
template<typename K = int, typename V = std::string>
std::ostream& operator<<(std::ostream& out, const HashNode<K, V>& node) {
    out << "[ " << "key: " << node.getKey() << ", " << "val: " << node.getValue() << " ]";
    return out;
}

//REM: then we stream it out
//HashNode<float, int> hNodeF = new HashNode<float, int>();
HashNode<>* hNode = new HashNode<>();
hNode->setKey(777);
hNode->setValue("lucky?");
std::cout << hNode << std::endl; // why only an address or reference show up, why does my overload operator not working?
delete hNode;
Posted
Updated 22-May-22 4:04am
v7

1 solution

C++
std::cout << *hNode << std::endl;
Your operator defined for reference but your object is a pointer.
 
Share this answer
 
v2
Comments
Phoenix Liveon 15-Jan-22 1:20am    
What am I doing?! I am really thankful for the Solution. This is my first three weeks of studying/doing c++. Now I remember when doing pointers there's this dereferencing and addresses. I am really grateful for the brisked Answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900