Search code examples
c++templatestemplate-templates

Template template parameters without specifying inner type


I want to know if it is at all possible to have code that has the following behaviour:

int main()
{
    func<vector>(/*some arguments*/);
}

That is, I want the user to be able to specify the container without specifying the type that it operates on.

For example, some (meta) code (which does not work with the above) that might define func would be as follows:

template<typename ContainerType>
int func(/*some parameters*/)
{
    ContainerType<int> some_container;
    /*
        operate on some_container here
    */
    return find_value(some_container);
}

Solution

  • The syntax is

    template <template <typename...> class ContainerType>
    int func(/*some parameters*/)
    {
        // Your code with ContainerType<int>
    }
    

    Note: class cannot be replaced by typename (until c++17).

    You cannot simply use typename instead of typename... Because std::vector takes Type and Allocator (defaulted): std::vector<T, Allocator>