Question

I want to achieve something like this with boost multi_index_container and composite_key:

struct LogicalAnd {
    bool operator()(const int& argVal1, const int& argVal2) const {
        return int(argVal1 & argVal2) == argVal1;
    }
};

template<class T, class Enable = void>
class FooContainer;

template <class T>
struct FooContainer<T,typename boost::enable_if<boost::is_base_of<IFoo, T> >::type> {
    typedef multi_index_container<
            boost::shared_ptr<T>,
            indexed_by<
            hashed_non_unique<
            composite_key<
            T,
            const_mem_fun<T,int,&T::getKey1>,
            const_mem_fun<T,int,&T::getKey2>
    >,
    composite_key_equal_to<
    LogicalAnd,
    LogicalAnd
    >
    >
    >
    > shared_ptr_type;
};

Knowing that:

namespace CustomKey {
    typedef enum {
        VAL1 = 0x00000001,
        VAL2 = 0x00000002,
        ALL = 0xFFFFFFFF
    } type;
}

The goal is to be able to perform the following:

container.find(boost::make_tuple(CustomKey::VAL1, CustomKey::ALL));

Which would allow me to retrieve all elements for which LogicalAnd returns true.

The problem is that I can't manage to get my LogicalAnd comparator to work with my multi_index_container.

I can get it to build by adding a composite_key_hash right before composite_key_equal_to:

composite_key_hash<
      boost::hash<int>,
      boost::hash<int>
>

But find operation does not work as expected so it does not change much...

I've searched boost documentation, and I've tryed various implementations, but I'm getting drown in the amount of information...

Any help is appreciated!

Was it helpful?

Solution

You're using a hash for your multi-index.

That means the LogicalAnd comparator never gets called unless something is found in the right hash bucket.

0x01 and 0xFF don't hash to the same value even though 0x01 & 0xFF == 0x01. That is, LogicalAnd would return true, but it's never invoked.

You would need a hash function which is invariant wrt. LogicalAnd, and I don't think that's possible. By design most hash functions are supposed to minimise collisions between different key values.

You need to come up with some different indexing system, I'm afraid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top