Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL container type as template parameter

Tags:

c++

c++11

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?

like image 949
Tomilov Anatoliy Avatar asked Jan 21 '13 11:01

Tomilov Anatoliy


People also ask

Are STL containers implemented as templates?

They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers).

Can we use non-type parameters as argument templates?

A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.


1 Answers

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.

like image 115
Andriy Tylychko Avatar answered Sep 19 '22 01:09

Andriy Tylychko