Tomilov Anatoliy
Tomilov Anatoliy

Reputation: 16691

STL container type as template parameter

I want to create the generic class template that uses internally a specific container to determine the different types. Something like this:

#include <vector>
#include <list>
template< typename F, template< class ... > class container_type = std::vector >
struct C
{
    C();
    template< typename U >
    C(container_type< U >);
    C(container_type< F >);
    C(container_type< int >);
    container_type< double > param;
};
C< unsigned, std::list > c;

What is the most natural way to do this? Say, whether you want to mention the presence of the container's allocator in any form?

Upvotes: 5

Views: 4194

Answers (1)

Andriy Tylychko
Andriy Tylychko

Reputation: 16256

something like this?

template< typename F, template<class T, class = std::allocator<T> > class container_type = std::vector >
struct C
{
    C() {}
    template< typename U >
    C(container_type< U >) {}
    C(container_type< F >) {}
    C(container_type< int >) {}

    container_type< double > param;
};

C< unsigned, std::list > c;

EDIT:

Similar but a bit simpler approach is used by std::queue which is parametrized by the type of container which will be used internally. Hopefully this proves this approach is quite natural. The sample above was tested in VC++10 and shows how to deal with an allocator.

Upvotes: 5

Related Questions