将任何原始指针传递给函数的目的是caller有一些想法:
作为输入参数的 C 样式字符串推断出后者,因为假设到达空字符终止符时就认为“有多少”。
但如果你是not传递 C 风格的字符串?如果它只是零个或多个的序列怎么办char
价值观?好吧,如果是这样的话,那么:
void f(const char *s)
{
// how many char does s refer to?
}
逻辑推论是这样做:
void f(const char *s, std::size_t N)
{
// Now the caller is telling us there are N chars at s
}
这一点也不罕见,尽管如果调用者向我们传递了错误的长度(永远不要说永远),则可能会出现潜在的错误。
但是如果有一种方法可以从实际变量中获取这些数据呢?type通过非类型模板参数使用推导传递给函数?如果调用者使用固定数组调用我们怎么办?
template<std::size_t N>
void f(const char(&ar)[N])
{
// we know the caller is passing a const-reference to a
// char array declared of size N. The value N can be used
// in this function.
}
现在我们知道列表中的两项:“什么”和“多少”。此外,我们现在可以提供both一个模板函数和一个overload并且我们可以使用两个世界:
// length specified implementation
void f(const char *s, std::size_t N)
{
// caller passed N
}
// fixed buffer template wrapper
template<std::size_t N>
void f(const char(&ar)[N])
{
f(ar,N); // invokes length-specified implementation from above.
}
以下两项都将起作用:
int main()
{
char buff[3];
f(buff,3);
f(buff);
}
那么这有多好呢?因为以下内容将标记编译器错误,因为找不到匹配的实现:
int main()
{
char buff[3];
const char *ptr = buff;
f(ptr); // ERROR: no matching function f(const char *)
}
总之,这是一种常见的技术,可以帮助向被调用者提供项目符号列表中的两项:“什么”和“多少”,而无需长期操作sizeof(ar)/sizeof(*ar)
每次使用固定长度的本机数组作为输入参数时。
祝你好运。