c++ – Why are template parameters needed?

Question:

Please give real examples of using these parameters, when they are indispensable or they greatly simplify the code.

Answer:

Let's look at the code below:

#include <vector>
#include <list>

using namespace std;

template <template <typename T> typename Cont>
class Foo
{
private:
    Cont<int> values;
};

template <typename Cont>
class Bar
{
private:
    Cont values;
};

int main()
{
    Foo<vector> fooVec;
    Bar<vector<int>> barVec;
    
    Foo<list> fooList;
    Bar<list<int>> barList;
    
    return 0;
}

As you can see, we can pass any container to both classes. So what's the difference? The difference is that we have the opportunity to pass a container of a different type to the Bar class. Nobody forbids us to write

Bar<list<double>> barList;

In turn, the Foo class allows the user of the class to choose the appropriate container for storing values, but does not allow the user to choose the type for these values.


Here is another use case. For example, you need to store two containers in a class object. And it is important for you that these are the same containers.

#include <iostream>
#include <vector>
#include <list>

template <typename Type1, typename Type2, template<typename T> typename Cont>
class Foo
{
private:
    Cont<Type1> first;
    Cont<Type2> second;
};

int main()
{
    Foo<int, double, std::vector> obj1;
    Foo<char, bool, std::list> obj2;
    
    return 0;
}

By passing a pattern as a parameter, you can ensure that first and second are the same containers.


This language feature is more commonly used in metaprogramming. Try to search on github for such libraries. But you can start with Boost . It contains MPL (Metaprogramming Library) , which has a quote* class template that uses template template parameter .
Synopsis :

template<
      template< typename P1 > class F
    , typename Tag = unspecified
    >
struct quote1
{
    // unspecified
    // ...
};

...

template<
      template< typename P1,... typename Pn > class F
    , typename Tag = unspecified
    >
struct quoten
{
    // unspecified
    // ...
};
Scroll to Top
AllEscort