零长度C-阵列结合指针类型 [英] Zero-length C-array binds to pointer type

查看:126
本文介绍了零长度C-阵列结合指针类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一个函数模板这需要一个C数组的引用:

I recently wrote a function template which takes a reference to a C-array:

template <class T, size_t N>
void foo(T(&c_array)[N]);

假设T是一个字符的C字符串的长度 N - 1 由于空终止子。我意识到,我也许应该处理的边缘情况下ñ== 0 ,因为那时 N - 1 的std :: numeric_limits&LT;的std ::为size_t&GT; :: MAX()

Assuming T is a char, the length of the C-string is N - 1 due to the null-terminator. I realized I should probably handle the edge-case where N == 0, because then N - 1 would be std::numeric_limits<std::size_t>::max().

因此​​,为了避免可能在极少数情况下随之而来,有人传递一个零长度数组此功能的混乱,我把一张支票ñ== 0

So in order to avoid the chaos that might ensue in the rare case that someone passes a zero-length array to this function, I placed a check for N == 0.

不过,出乎我的意料,似乎一个长度为零的数组实际上是连数组类型 - 或者至少,这就是GCC似乎相信。事实上,一个零长度数组不连的绑定的上述功能的签名,如果有一个指针类型签名功能可作为候选。

However, to my surprise, it seems that a zero-length array is actually not even an array type - or at least, that's what GCC seems to believe. In fact, a zero-length array doesn't even bind to the above function signature, if a function with a pointer-type signature is available as a candidate.

考虑以下code:

template <class T, size_t N>
void foo(T(&array)[N])
{
    std::cout << "Array" << std::endl;
}

void foo(const void* p)
{
    std::cout << "Pointer" << std::endl;
}

int main(int argc, char** argv)
{
    char array1[10] = { };
    const char* pointer = 0;
    char array2[0] = { };

    foo(array1);
    foo(pointer);
    foo(array2);
}

使用GCC 4.3.2,这个输出:

With GCC 4.3.2, this outputs:

Array
Pointer
Pointer

奇怪的是,零长度数组prefers绑定到需要的指针类型的功能。所以,这是海湾合作委员会中的错误,或者是有由C无授权的一些​​模糊的原因++标准,为什么这种行为是必要的吗?

Oddly, the zero-length array prefers to bind to the function that takes a pointer type. So, is this a bug in GCC, or is there some obscure reason mandated by the C++ standard why this behavior is necessary?

推荐答案

由于数组必须具有大于零的长度,如果你的编译器错误地接受零大小的数组的定义,那么你很安全的范围之外的语言标准。有没有必要为你处理的边缘情况ñ== 0

As arrays must have greater than zero length, if your compiler erroneously accepts a definition of a zero-sized array then you're "safely" outside of the scope of the language standard. There's no need for you to handle the edge case of N == 0.

这是用C ++真:8.3.5 [dcl.array]:如果恒恩pression(5.19)是present,它应是一个整型常量前pression及其价值应大于零。

This is true in C++: 8.3.5 [dcl.array]: If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

这篇关于零长度C-阵列结合指针类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆