I’m a beginner at templates in C++ and I would like to know if it’s possible to pass a container to the typename of a template function, here is what I’m trying to do:
template <typename T>
int find_size(const T<int> t)
{
return (t.size());
}
int main(void)
{
std::array<int, 10> test;
for (int i = 0; i < 10; i++)
{
test[i] = i;
}
findsize(test);
}
When I’m compiling I get an error saying that T isn’t a template.
Is it possible to pass the template of a container to the template of a function?
>Solution :
With minimum changes to make it work, your code could be this:
#include <array>
template <typename T>
int find_size(const T& t)
{
return (t.size());
}
int main(void)
{
std::array<int, 10> test;
for (int i = 0; i < 10; i++)
{
test[i] = i;
}
find_size(test);
}
basically I want my function to be able to take an abritary type of container
Thats exactly what the above does. It works for any container type T that has a size().
If you actually want to parametrize find_size on a template rather than a type, then you can use a template template parameter:
#include <array>
template <template<class,std::size_t> class C>
int find_size(const C<int,10>& t)
{
return (t.size());
}
int main(void)
{
std::array<int, 10> test;
for (int i = 0; i < 10; i++)
{
test[i] = i;
}
find_size<std::array>(test);
}
However, using this is either more complicated than illustrated here, or of more limited use than the above: For the function parameter you need a type not just a template, and this find_size will only work with a template C that has 2 parameters, one type and one non-type parameter of type size_t (and I am actually not aware of any other container but std::array with that template parameters).
TL;DR: This is not a use case where a template template parameter is needed.
Is it possible to pass the template of a container to the template of a function?
Yes, but you don’t need it here.