Since sizeof and templates are both compile-time. What is it about the second parameter of the template that determines the size without specifying it in the caller function?
template <typename T, size_t n> bool isInHaystack(const T (&arr)[n], const T &needle)
{ /* I know const references are best with strings and non-primitives and should
     be mitigated when using ints as in the example.*/
    size_t i, size = sizeof arr / sizeof T; // how does it know n is the size?
    for (i = 0; i < size; ++i)
        if (arr[i] == needle)
            return true;
    return false;
}
int main(int argc, char **argv) {
    int arr[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };
    cout << isInHaystack(arr, 7) << endl;
    isInHaystack<int, (size_t)(sizeof(arr) / sizeof(int))>(arr, 7); // this works, too
    return 0;
}
How does this size_t n get its value when passing an array? How does it know without providing it explicitly?
To make this a little more clear, this will not compile:
template <typename T> bool foo(const T(&arr)[], const T needle) {
    cout << sizeof arr << endl;
    return true;
}
int main(){
    int arr[] = {1,2,3};
    foo(arr, 1); // Error: could not deduce template argument for 'const T (&)[]' from 'int [21]'
}
What is the issue?
 
    