boostorg / unordered

Boost.org unordered module
http://boost.org/libs/unordered
Boost Software License 1.0
63 stars 56 forks source link

[FR] Unified hash and equality predicate (stateful) objects #232

Open psiha opened 9 months ago

psiha commented 9 months ago

Consider a usecase with stateful comparators and hashers where they both share the same state (IOW they are the same object providing two functions - one for hashing and one for comparison) - would you consider adding this possibility? For example by adding an empty 'flag' comparator type SameAsHasher (or something to that effect)?

(to avoid the duplication or 'smaller' duplication where the hasher and comparator store a reference to an external object as well as the associated more complex codegen)

cmazakas commented 9 months ago

Hmm, I think if I understand correctly, you just want something like this:

#include <boost/unordered/unordered_flat_map.hpp>
#include <memory>

template<class T>
struct unified {
    struct state;
    std::shared_ptr<state> p_;

    bool operator()(T const& lhs, T const& rhs) const {
        return lhs == rhs;
    }

    std::size_t operator()(T const&) const noexcept {
        return 0;
    }
};

int main() {
    using map_type =
        boost::unordered_flat_map<int, int, unified<int>, unified<int>>;

    map_type map;
    map.emplace(1,2);
    return map.empty() ? 255 : 0;
}

This should already be supported the library. Otherwise, I might need some pseudocode to fully understand the request.

pdimov commented 9 months ago

Presumably the idea is to avoid the dynamic allocation of state, although since the map already allocates, it's not clear how much this would save in practice.

psiha commented 8 months ago

It isn't about avoiding allocation or shared_ptr bloat as it isn't necessary. As mentioned above it is about avoiding the: