Home > Mobile >  Pass a container type as the typename of a template in c
Pass a container type as the typename of a template in c

Time:11-17

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?

CodePudding user response:

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.

CodePudding user response:

You can pass your type to your templatized function. The compiler will check if the calls to this function are valid or not (i.e.: it will check if each call to your function is done with an object that has a size() method).`

I fixed your code, try if this works (untested)

template <typename T>
int find_size(const T &v)
{
    return int(v.size());
}

int main()
{
    std::array<int, 10> test;
    for (int i = 0; i < 10; i  )
    {
        test[i] = i;
    }
    find_size(test);
    return 0;
}

CodePudding user response:

T is a type name, so calling .size() doesn't really make sense here.

Why are you trying to use templates if you want a parameter with a type? You could type cast your return.

try

template <typename T>
int find_size(T a)
{
return (int) a.size();
}
  • Related