templatesc++14autoranged-loops

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


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.


Solution

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