2

Is it possible and how to use std::shared_ptr<std::string> implicitly as index for boost::multi_index_container?

This code

struct Item
{
    std::shared_ptr<std::string> shared_id;
};

using ItemsIndexed = boost::multi_index_container<
    Item,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_non_unique<
            boost::multi_index::member<Item, std::string, &Item::shared_id>>>>;

(compiler explorer link)

gives an error value of type 'std::shared_ptr<std::string> Item::*' is not implicitly convertible to 'std::string Item::*'

Or the only way is to provide the key extractor that will dereference shared_pointer:

struct Item
{
    std::shared_ptr<std::string> shared_id;
    std::string shared_id_extractor() const
    {
        return *shared_id;
    }
};

using ItemsIndexed = boost::multi_index_container<
    Item,
    boost::multi_index::indexed_by<
        boost::multi_index::ordered_non_unique<
            boost::multi_index::
                const_mem_fun<Item, std::string, &Item::shared_id_extractor>>>>;

(compiler explorer link)

uni
  • 539
  • 1
  • 9
  • 21
  • 1
    Don't crack the compiler explorer with the flag `-I/opt/compiler-explorer/libs/boost_1_71_0`. Enable Boost in Libraries: https://godbolt.org/z/1ashE4h3b. The errors are clear now. – 273K May 11 '23 at 17:44
  • Thank you for the advice. I've updated links. – uni May 12 '23 at 07:43

1 Answers1

1

This depends on what exactly you want to use as key:

  • member<Item, std::shared_ptr<std::string>, &Item::shared_id> will use pointers as keys, that is, two elements are equal if they point to the same string.
  • const_mem_fun<Item, std::string, &Item::shared_id_extractor> will use the actual strings as keys, that is, two elements are equal if the strings pointed to compare equal. I understand it's this last option you're after, but I felt like mentioning the other one just in case. There's no simpler way to use strings as keys (for your scenario) than you described. You can avoid creating temporary strings this way: https://godbolt.org/z/ehjvvfxP1
Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20