Search code examples
c++templatesclass-template

Template class as template parameter default parameter


Today I tried to pass a template class to a template parameter. My template class std::map has four template parameters, but the last two of them are default parameters.

I was able to get the following code to compile:

#include <map>

template<typename K, typename V, typename P, typename A,
    template<typename Key, typename Value, typename Pr= P, typename All=A> typename C>
struct Map
{
    C<K,V,P,A> key;
};

int main(int argc, char**args) {
    // That is so annoying!!!
    Map<std::string, int, std::less<std::string>, std::map<std::string, int>::allocator_type, std::map> t;
    return 0;
}

Unfortunately, I don't want to pass the last two parameters all the time. That is really too much writing. How can I use here some default template arguments?


Solution

  • You could use type template parameter pack (since C++11) to allow variadic template parameters:

    template<typename K, typename V,
        template<typename Key, typename Value, typename ...> typename C>
    struct Map
    {
        C<K,V> key; // the default value of template parameter Compare and Allocator of std::map will be used when C is specified as std::map
    };
    

    then

    Map<std::string, int, std::map> t;