Is it possible to have dynamic polymorphism for operators? I have a vector of base-class pointers:
std::vector<Event*> events;
where each event is a different derived class (e.g. StartEvent). All derived classes have their operator<< implemented such that they can be printed to the console.
However, this does't work:
std::for_each(events.cbegin(), events.cend(), [] (const Event *ev) {
std::cout << *ev << std::endl;
});
I get this error:
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const Event’)
std::cout << *ev << std::endl;
I tried this:
class Event {
protected:
Event() { }
virtual std::ostream& operator<< (std::ostream &stream);
public:
const int32_t timestamp;
};
which didn't help. Is it a problem, if operator<< is implemented as a friend in the derived classes?
friend std::ostream& operator<< (std::ostream &stream, const StartEvent& se) {
/* do stuff */
}