zehelvion zehelvion - 4 months ago 11
C++ Question

Supersede Existing operator<<: Override Existing Implementation

A function like this exists:

std::ostream& operator<< (std::ostream &out, const boost::dynamic_bitset<> &v) {
for (unsigned i = 0; i < v.size(); ++i) {
out << int(v[i]);
}
return out;
}


Wish to override it and use something like this. :)

std::ostream& operator<< (std::ostream &out, const boost::dynamic_bitset<> &v) {
for (unsigned i = 0; i < v.size(); ++i) {
if (i && v[i]) {
out << ", " << i;
}
}
return out;
}


Obviously C++ is not going to allow this. How do you overcome this and use an alternative logging functionality?

Answer

As opposed to @Bathseba's (correct) answer, I would avoid inheriting from the class: it is never really trivial as you might need several ctors, you might want wish to redirect differently in different settings, there might be other operations which you wish to specialize (like the redirection here), and so forth.

Instead, I would create a class just for redirection:

struct my_redirector
{
    my_redirector(const whatever &w) : m_w(w) {}
    const whatever &m_w;
};

std::ostream &operator<<(std::ostream &&os, const my_redirector &r)
{
     // whatever you want
     return os;
}

which you would use as:

whatever w;

cout << my_redirector(w) << endl;

The code is short enough in order to see, at a glance, why you created this class.