传递模板数组时 sizeof 是如何工作的?

How does sizeof work when passing a template array?

因为 sizeof 和模板都是编译时的。 template 的第二个参数决定大小而不在调用函数中指定它是什么?

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;
}

这个size_t n在传递数组时如何获取它的值?不明确提供它怎么知道?

为了更清楚一点,这不会编译:

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]'
}

问题是什么?

如果你问的是"how does the compiler know to put the array size into n"...表达式

const T (&arr)[n]

正在通过

int arr[11]

因此可以推断出 Tintn11.

如果你问它怎么知道 arr 有多大...

int arr[] = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 };
cout << isInHaystack(arr, 7) << endl;

arr 是一个数组。编译器知道它有多大。如果您认为 "arr is really just a pointer",那是不对的。据说数组和指针具有 等价性 (参见 K&R 第 5.3 节),这并不意味着它们相同,而是它们在有限数量的上下文中导致相同的行为。

在 C 和 C++ 中,数组能够衰减为指针,但在衰减发生之前它们仍然不是指针。

int arr[] = { 1, 3, 5, 7 };
int* arrp = arr; // decay
cout << isInHaystack(arr, 7); // Error.

http://c-faq.com/aryptr/aryptrequiv.html