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?
Templates Specialization is defined as a mechanism that allows any programmer to use types as parameters for a class or a function. A function/class defined using the template is called a generic function/class, and the ability to use and create generic functions/classes is one of the critical features of C++.
Templates are powerful features of C++ which allows us to write generic programs. We can create a single function to work with different data types by using a template.
Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes. The following function template swaps two items: C++ Copy.
The main type of templates that can be implemented in C are static templates. Static templates are created at compile time and do not perform runtime checks on sizes, because they shift that responsibility to the compiler.
Is there a specific reason for you to use a template template? Why not just like this?
template <typename Container>
void print_size(Container const& a)
{
cout << a.size() << endl;
}
In general, template templates aren’t worth the trouble. In your particular case, there certainly is no use for them, and if you really need to access the member type, I suggest you bow to common practice and use a metafunction (typename Container::value_type
in this case).
I know that the question was asked long time ago , but i had same problem , and the solution is that you need to write
template <template <typename,typename> class Container, typename element, typename Allocator>
void print_size(Container<element, Allocator> & a)
{
std::cout << a.size() << std::endl;
}
because the vector has two template parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With