Is it possible to overload the << operator for a custom class in a way that all of following will work:
CustomClass customClass;
std::shared_ptr<CustomClass> sharedPointer(customClass);
os << customClass;
os << sharedPointer;
Or that at least following works:
os << sharedPointer.get();
By default, using the common technique to overload the operator, only following 2 options will work:
os << customClass;
os << *sharedPointer.get();
Edit
"working" here means, that in all cases the custom classes << operator overload is executed and that I get the result of os << customClass in all cases instead of pointer addresses in the case of the pointer classes
Example
Code:
os << customClass;
os << sharedPointer;
os << sharedPointer.get();
os << *sharedPointer.get();
Output:
Custom class text
00000244125655C0
00000244125655C0
Custom class text
Desired:
At second or third output should be "Custom class text" as well
that in all cases the custom classes << operator overload is executed and that I get the result of os << customClass in all cases instead of pointer addresses in the case of the pointer classes
Here's how I would do it:
#include <iostream>
#include <string>
#include <memory>
class MyClass {
std::string s;
friend std::ostream& operator<<(std::ostream& os, const MyClass& c) {
os << c.s;
return os;
}
public:
MyClass(const std::string& s_) : s(s_) {}
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::shared_ptr<T>& pc) {
os << pc.get() << " " << *pc;
return os;
}
int main() {
std::shared_ptr<MyClass> pc = std::make_shared<MyClass>("Hello");
std::cout << pc << std::endl;
}
Output
0x20f5c30 Hello
See a live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With