Boost logo

Boost Users :

Subject: [Boost-users] Using hash_range with polymorphism
From: Kelvin Chung (kelvSYC_at_[hidden])
Date: 2011-12-01 02:48:51


I'm having a hard time reconciling two distinct notions. Suppose I
have a class hierarchy with root class Foo, and subclasses Foo1, Foo2,
etc. (all of which are leaf classes) Now, suppose that hash_value() is
defined for all the subclasses but not Foo itself (say, if Foo was
abstract).

Now suppose I have this:

struct FooList {
        std::vector<boost::shared_ptr<Foo>> foos;
}

std::size_t hash_value(const FooList& list) {
        std::size_t seed = 0;
        
        typedef
boost::indirect_iterator<std::vector<boost::shared_ptr<Foo>>::const_iterator>
Iterator;
        boost::hash_range(seed, Iterator(list.foos.begin()),
Iterator(list.foos.end());
        
        return seed;
}

This seems a bit incorrect (and it would fail to compile due to
"ambiguous overload" of hash_combine or something). What I want to do
is something along the lines of

std::size_t hash_value(const FooList& list) {
        std::size_t seed = 0;
        
        for (std::vector<boost::shared_ptr<Foo>>::const_iterator it =
list.foos.begin(); it != list.foos.end(); ++it) {
                boost::hash_combine(seed, **it);
        }
        
        return seed;
}

That is, hash the Foos pointed to by the foos (using the correct
derived class hash_value() functions) and not the shared_ptrs
themselves. Is there a "shorter" version of the latter (which I
presume is correct), or will the latter have to do?


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net