Home > Mobile >  Templatizing a parameter for a function in C
Templatizing a parameter for a function in C

Time:11-30

I'm a beginner for programming and read an example codes, while I was learning about algorithm with C .

template <size_t N>
void print(const std::array<int, N>& arr)
{
    for(auto element: arr)
    {
        std::cout << element << ' ';
    }
}

Now I'm curious what the difference is for the templatizing like above and just passing the parameter like below.

void print(const std::array<int, size_t>& arr)

Does work they same? If yes, is there an advantage to write codes like the first example? If not same, could explain, what the difference between them is?

I guess there is no difference between them maybe..?

CodePudding user response:

Does work they same?

No, the second snippet with std::array<int, size_t> won't even compile because the second template parameter of std::array is a non-type template parameter of type std::size_t and so it expects an argument of type size_t(or convertible to it).

Thus, size_t is not a valid template argument for the second non-type parameter and hence the second snippet won't compile.

//--------------vvvvvv------>invalid argument for a non-type parameter 
std::array<int, size_t>
  • Related