【发布时间】:2016-01-23 20:25:27
【问题描述】:
我正在尝试了解模板功能。最终目标是将整个数组传递给函数。似乎有很多不同的方法可以实现这一点,但它们都使用模板函数。这是我发现的最简单的示例之一...
template<size_t N>
void h(Sample (&arr)[N])
{
size_t count = N; //N is 10, so would be count!
//you can even do this now:
//size_t count = sizeof(arr)/sizeof(arr[0]); it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!
我以为模板是用来创建一个变量,可以用来代替int、float、char等。指定类型(size_t)有什么意义,这是做什么的?
【问题讨论】:
-
“最终目标是将整个数组传递给函数”。使用 std::array 或 std::vector。
-
@n.m.传递
std::array可能仍然需要在数组长度上模板化的函数 - 所以即使修复了这个问题,问题仍然相关。
标签: c++ templates template-argument-deduction