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]'
}
问题出在哪里?
如果你问"编译器怎么知道把数组大小放到 n 中"......表达式
const T (&arr)[n]
正在通过
int arr[11]
因此,它能够推断出T
是int
的,n
是11
的。
如果你问它怎么知道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
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?