When passing containers by reference, is auto parameter or template deduction better?

68 Views Asked by At

What are the differences, if any, between

template <typename T, int N>
void input (T (&Array) [N])
{
    for (T& val: Array) cin >> val;
}

and

template <typename T>
void input (T (&Array))
{
    for (auto& val: Array) cin >> val;
}

and

void input (auto& Array)
{
    for (auto& val: Array) cin >> val;
}

?

Which is better?

All of them work correctly with double store[5] but not with vector <double> store

Side note: The first version won't compile with T (&Array) [] since that is a "reference to array of unknown bound". The second won't compile if we wrote T& val: Array instead.

2

There are 2 best solutions below

0
On BEST ANSWER

As Frank pointed out, the first version takes in arrays only, while the second and third can also take in a vector or list

The second and third versions don't seem to work with vector <double> store because the for loop is not executed when the vector is empty.

Replace it with vector <double> store (5, 0) instead.

0
On

In the case of an array argument, these all have the same behaviour. In the first one T is deduced to the element type; in the others, T or auto deduces to the array type.

Of course, the second and third forms (which are equivalent except that you can't write a specialization for the auto one) permit non-array arguments to be passed.