mercredi 26 août 2020

C++11: parameter pack to pass in to constructor for templatized memory allocator

Say I have a class Allocator with a method that will allocate space somehow, construct a desired object in that space, and then do something with the constructed object. The objects' classes are heterogeneous: we could be called for multiple classes in one build. In short I need an idea how to write the ??? parts in this example code:

class Foo {
    Foo( int i, double d, string s );
};

class Bar {
    Bar( int i );
};

class Allocator {
    template<typename T> Allocate( ??? );
}

template<typename T> Allocator::Allocate( ??? ) {
    void* pv = /* memory is found somehow, perhaps using sizeof( T ) */;

    T* pobj = new( pv ) T( ??? );

    /* something is done with the new object */
}

/* user of this class would write something like this??? */
allocator.Allocate<Foo>( 1, 2.3, "four" );
allocator.Allocate<Bar>( 1 );

I've looked at initializer_list<> and parameter packs, but I'm not seeing how to combine those with the template method.

Aucun commentaire:

Enregistrer un commentaire