Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a container type as the typename of a template in c++

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading