What are some uses of template template parameters?

后端 未结 10 1098
无人共我
无人共我 2020-11-22 03:41

I\'ve seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses do

10条回答
  •  执笔经年
    2020-11-22 03:52

    It improves readability of your code, provides extra type safety and save some compiler efforts.

    Say you want to print each element of a container, you can use the following code without template template parameter

    template  void print_container(const T& c)
    {
        for (const auto& v : c)
        {
            std::cout << v << ' ';
        }
        std::cout << '\n';
    }
    

    or with template template parameter

    template< template class ContainerType, typename ValueType, typename AllocType>
    void print_container(const ContainerType& c)
    {
        for (const auto& v : c)
        {
            std::cout << v << ' ';
        }
        std::cout << '\n';
    }
    

    Assume you pass in an integer say print_container(3). For the former case, the template will be instantiated by the compiler which will complain about the usage of c in the for loop, the latter will not instantiate the template at all as no matching type can be found.

    Generally speaking, if your template class/function is designed to handle template class as template parameter, it is better to make it clear.

提交回复
热议问题