c++syntaxtemplate-templates

How do I specify a default value for a template template parameter?


I have a function which takes a template template parameter, e.g.:

template <template <typename K, typename V> typename Map>
void foo();

I want to specify a default value for Map; namely, std::unordered_map<K,V>, which indeed has two template parameters itself. What's the syntax for that?


Solution

  • The syntax is for you to use just the name of the template you want, without any angle brackets.

    So, for your example, you would write:

    #include <unordered_map>
    
    template <template <typename K, typename V> typename Map = std::unordered_map>
    void foo();
    

    and this should compile. Full example program:

    #include <unordered_map>
    #include <iostream>
    
    template <template <typename K, typename V> typename Map = std::unordered_map>
    int foo() { 
        return sizeof(Map<int, double>);
    }
    
    int main() {
        std::cout << "size of (std::unordered_map<int, double> is: "
            << sizeof(std::unordered_map<int,double>) << '\n';
        std::cout << "size of default Map<int, double> is: " << foo() << '\n';
    }
    

    GodBolt.