mercredi 5 août 2015

How to avoid code duplication between similar const and non-const member functions which pass class members to callbacks?

This is a specific case of this question where that answer doesn't directly work.

Consider:

struct hurg {};

class furg {
public:
    template <class F>
    void for_each_hurg(F&& f) const {
        for (auto& h : hurgs) {
            f(h);
        }
    }

    template <class F>
    void for_each_hurg(F&& f) {
        for (auto& h : hurgs) {
            f(h);
        }
    }
private:
    std::vector<hurg> hurgs;
};

Usage:

furg f;
const auto& cf = f;

f.for_each_hurg([](hurg& h) { });
cf.for_each_hurg([](const hurg& h) { });

The code for the const and non-const versions is identical, but only because auto& h infers const hurg& in the first case and hurg& in the second case.

In the spirit of the previously-linked-to Scott Meyers' solution, I came up with the following:

template <class F>
void for_each_hurg(F&& f) {
    const_cast<const furg&>(*this).for_each_hurg([&f](const hurg& h) {
        f(const_cast<hurg&>(h));
    });
}    

However, this seems like it could be more trouble than it's worth, especially if the types are long and if I can't use C++14's generic lambdas.

Aucun commentaire:

Enregistrer un commentaire