Template C ++ Function

How to write a template function that works on an arbitrary container of an arbitrary type? For example, how can I generalize this dummy function

template <typename Element>
void print_size(const std::vector<Element> & a)
{
    cout << a.size() << endl;
}

to

template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
    cout << a.size() << endl;
}

Here is a typical use

std::vector<std::string> f;
print_size(f)

It gives an error

tests/t_distances.cpp:110:12: error: no matching function for call to ‘print(std::vector<std::basic_string<char> >&)’. I'm guessing I must tell the compiler something more specific about what types that are allowed.

What is the name of this use case for the template and how to fix it?

+5
source share
5 answers

Is there a specific reason for using a template template? Why not just like that?

template <typename Container>
void print_size(Container const& a)
{
    cout << a.size() << endl;
}

In general, template templates arent worth the problem. In your particular case, it is definitely useless for them, and if you really need to access the type of participant, I suggest you bow to the usual practice and use the metafunction ( typename Container::value_typein this case).

+13

, vector , , . - Container :

template <typename Container>
void print_size( Container const & c ) {
   std::cout << c.size() << std::endl;
}

, ( Container, value_type value_type, Element...). , ( , )...

+3

, , , ,

template <template <typename,typename> class Container, typename element, typename Allocator>
void print_size(Container<element, Allocator> & a)
{
    std::cout << a.size() << std::endl;
}

since the vector has two template parameters

+2
source

Why use something like

template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
    cout << a.size() << endl;
}

? Use it in a simpler way:

template<typename Container>
void print_size(const Container & a)
{
    cout << a.size() << endl;
}

When called, print_size(f)you call print_sizewith Container vector<string>.

+1
source

For these types of general algorithms, I always prefer iterators, i.e.

template <typename IteratorType>
void print_size(IteratorType begin, IteratorType end) {
   std::cout << std::distance(begin, end) << std::endl;
}

To call:

std::vector<std::string> f;
print_size(f.begin(), f.end());
0
source

All Articles