Slava
Slava

Reputation: 44288

boost::multi_index multiple keys from the same object

Let's say I have an object, that can be identified by different names from different namespaces:

enum Namespace {
    nspaceA,
    nspaceB
};

struct Object {
    int id;
    std::map<Namespace, std::string> names;
};

Now I want to store instances of Object in boost::multi_index and being able to find an object by unique id as well as namespace/symbol pair:

array.find( boost::make_tuple( nspaceA, "foobar" ) );

So candidate would be a composite key, and as much as I understand, one object can represent only one key. But one Object instance has names in different namespaces. Is there a way to solve this with boost::multi_index array?

Upvotes: 1

Views: 351

Answers (2)

Considering that Namespacehas only two values, wouldn't you be better off defining Object like this?

struct Object {
    int id;
    std::string nameA,nameB; // potentially empty
};

In this case, Objectscan be easily indexed by id, nameA and nameB.

Upvotes: 0

villintehaspam
villintehaspam

Reputation: 8734

You can store multiple objects in the container, where each object references the original object you want to store.

So for instance if you have an object of type Foo that can be referenced by several different keys, where each key is a namespace + name pair, then you can for instance store objects of type

struct Key {
  Namespace namespace;
  std::string name;
  std::shared_ptr<Foo> object;
};

instead of storing Foo objects directly.

Update (after the question was updated): If you need to look up the objects in other ways such as by id, then you will either need to make the index non-unique or store the objects in a secondary container.

Another option could be to separate the namespaces into different indexes on the container, which of course doesn't work in all scenarios either.

Upvotes: 1

Related Questions