c++template-meta-programmingfactory-patternabstraction

C++ factory of a container type without defining the container element type


Based on this topic, I wonder if it would be possible to have a factory class that would provide a container type, without defining the type of element of the container.

Something like:

template <typename t_container>
class factory {
public:
  using container = t_container;
}

so that something like this, but not exactly with this syntax because I know it is not valid in C++, would work:

...
factory<std::vector>::container<int> my_container;
...

The idea is that factory would define the type of container, but not the type of element that factory::container would contain, leaving that decision to the user code.


Solution

  • You want t_container to be a template, hence template <typename t_container> is wrong (it declares t_container to be a type, but std::vector is not a type). And after fixing that, your using declaration isnt right, because it assumes t_container is a type.

    You can do that by using a template template argument:

    #include <vector>
    
    
    template <template <typename...> class C>
    struct factory {
        template <typename T>
        using container = C<T>;
    
        template <typename T> 
        container<T> make() { return C<T>{};}
    
    };
    
    
    int main ()
    {
       auto vec_int = factory<std::vector>{}.make<int>();
    }
    

    Live Demo

    The same factory<std::vector> can make vectors with different element type as illustrated by the member alias template and member function template.

    There is only one small issue, when using container with non-type template arguments. The above will not work for std::array, because its 2nd argument is a size_t not a type. Also eg std::map is not covered by the above, because its element type is specified by 2 parameter (key and value type).