mardi 5 mai 2015

Template function to handle nested std::any_of

Consider this code:

#include <iostream>
#include <vector>
#include <algorithm>

struct Animal { virtual ~Animal() = default; };
struct Dog : Animal {};

struct Person {
    std::vector<struct Toddler*> children;
    const std::vector<Toddler*>& getChildren() const {return children;}
};

struct Toddler : Person {
    std::vector<Animal*> pets;
    const std::vector<Animal*>& getPets() const {return pets;}
};

int main() {
    Person* bob = new Person;
    Toddler* tom = new Toddler;
    tom->pets.push_back(new Dog);
    bob->children.push_back(tom);
    std::vector<Person*> people = {tom, bob};
    // Output: Does anybody in 'people' have a child that has a pet that is a dog?
    std::cout << std::boolalpha << std::any_of(people.begin(), people.end(),
        [](const Person* p) {return std::any_of(p->getChildren().begin(), p->getChildren().end(),
            [](const Toddler* t) {return
                std::any_of(t->getPets().begin(), t->getPets().end(),
                    [](const Animal* a) {return dynamic_cast<const Dog*>(a) != nullptr;});
            });
        }) << std::endl;  // true
}

My goal is to rewrite the above output using a template function something along the lines of

std::cout << anyOf (people, &Person::getChildren, &Toddler::getPets,
    [](const Animal* a) {return dynamic_cast<const Dog*>(a) != nullptr;}) << std::endl;

Thus only one lambda function needs to be specified, and everything else is much easier to read and write too. Here is what I have so far, but it is going horribly wrong:

#include <type_traits>

template <typename...> struct AnyOf;

template <typename Predicate, typename... A>
bool anyOf (Predicate pred, const A&... a) {
    return AnyOf<Predicate, A...>::execute (pred, a...);
}

template <typename Predicate, typename Container>
struct AnyOf<Predicate, Container> {
    static bool excecute (Predicate pred, const Container& c) {
        return std::any_of (c.begin(), c.end(), [pred](const typename Container::value_type& x) {return pred(x);});
    };
};

template <typename Predicate, typename Container, typename First, typename... Rest>
struct AnyOf<Predicate, Container, First, Rest...> : AnyOf<Predicate, typename std::result_of<First(void)>::type, Rest...> {
    using Base = AnyOf<Predicate, typename std::result_of<First(void)>::type, Rest...>;  // ???
    static bool excecute (Predicate pred, const Container& c, First first, Rest... rest) {
        return std::any_of (c.begin(), c.end(), [pred](const typename Container::value_type& x) {
            return Base::execute (pred, (x->*First)(), rest...);});  // ???
    };
};

Can anybody help me finish this? Or come up with a new design altogether?

Aucun commentaire:

Enregistrer un commentaire