jeudi 23 juin 2016

Memory pool with arbitrary number of containers

I have a memory pool that looks like so:

template<typename TreeType>
class LeafMemoryPool
{
public:
    void stealNodes(TreeType& tree);
    Leaf* getNode();
private:
    std::vector<Leaf*> mLeafs;
}

In my program I have different TreeTypes, like FloatTree and Vec3Tree, and I create a memory pool for each tree type. However, passing these around is a little annoying, and I would prefer a single memory pool that handles all of the different types. Also, I might need to add additional types in the future and I would like for it to be as dynamic as possible. Is this something that could be done with variadic templates? I have never used them before, and I do not know if this is what they could be used for.

The scenario I'm thinking of could be written in pseudo-code as

template<typename... TreeTypes>
class MemoryPool
{
public:
    // The template is only valid if the same type was declared
    // in TreeTypes above
    template<typename TreeType>
    void stealNodes(TreeType& tree)
    {
        // Somehow need to access the right std::vector that
        // stores TreeType::Leaf. This function will be called
        // a lot, and needs to be determined at compile time
        // for it to be useful.
    }

    template<typename TreeType>
    typename TreeType::Leaf* getNode();
private:
    // One for each TreeType in TreeTypes.
    // The leaf type can be deduced by
    // typename TreeType::Leaf
    std::vector<LeafArg1*> mLeafsForArg1;
    std::vector<LeafArg2*> mLeafsForArg2;
    ...
}

Everything above should be able to be determined at compile time. Can I solve this with some C++ template magic?

Aucun commentaire:

Enregistrer un commentaire