sizeof 在传递模板数组时如何工作

How does sizeof work when passing a template array?

本文关键字:何工作 工作 数组 sizeof      更新时间:2023-10-16

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

问题出在哪里?

如果你问"编译器怎么知道把数组大小放到 n 中"......表达式

const T (&arr)[n]

正在通过

int arr[11]

因此,它能够推断出Tint的,n11的。

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

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

arr是一个数组。编译器知道它有多大。如果你认为"arr实际上只是一个指针",那不是真的。数组和指针据说具有等价性(参见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