0

I'm trying to generate a unique index for each typename. This generation needs to work across shared library meanings that it has to be done at runtime.

Example:

size_t id0 = componentSection<Type1>();
size_t id1 = componentSection<Type2>();
size_t id2 = componentSection<Type1>();
return (id0 == id2 && id1 != id0 && id1 != id2);

I use a static variable in template.

Code suggestion:

private:
    template<typename C>
    size_t generateNewSection() noexcept
    {
        m_componentLists.emplace_back(std::make_unique<ComponentList<C>>());
        return m_componentLists.size() - 1;
    }

public:
    template<typename C>
    size_t componentSection() noexcept
    {
        static size_t section = generateNewSection<C>();
        return section;
    }

As you can see, I use the initialization property of static to make sure the index remains the same.

Problem:

Generated index are not the same across shared libraries because the static variable is "regenerated" for each library. I should move the static definition in a source file to make sure the address will be the same. But I can't because I use templates ... Each static variables can't be linked. I don't know how to solve this problem.

Thanks.

EDIT

My question has been set to deplicated but I still don't kown how to solve my problem. I understand the problem of static with shared library but is there a solution ?

Solution

I finally decided to choose this solution:

private:
    std::unordered_map<std::type_index, size_t> m_indexes;

    template<typename C>
    size_t getSection() noexcept
    {
        std::type_index index = std::type_index(typeid(C));

        if(m_indexes.find(index) != m_indexes.end())
            return m_indexes.at(index);

        m_componentLists.emplace_back(std::make_unique<ComponentList<C>>());
        m_indexes[index] = m_componentLists.size() - 1;

        return m_componentLists.size() - 1;
    }

public:
    template<typename C>
    size_t componentSection() noexcept
    {
        static size_t section = getSection<C>();
        return section;
    }
herotom99
  • 1
  • 2

0 Answers0