How do I write a template function that operates on a arbitrary container of a arbitrary type? For example how do 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 usage
std::vector<std::string> f;
print_size(f)
This give 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 this variant of template-use called and how do I fix it?
vector
takes two template arguments, not one, so the template template parameter needs to be modified. The rest of the answers suggest using either a normal template parameter or, as of C++20, just theauto
keyword. – Evesham