Zero-length C-array binds to pointer type

前端 未结 6 1204
误落风尘
误落风尘 2020-12-17 20:10

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

template 
void foo(T(&c_array)[N]);

相关标签:
6条回答
  • 2020-12-17 21:00

    The GCC Manual has a whole thing on zero length arrays. This is a GCC extension as is somewhat analogous to incomplete arrays.

    0 讨论(0)
  • 2020-12-17 21:04

    Apparently ISO C forbids 0-length arrays, which is probably affecting how GCC tries to compile stuff. See this question for further details! zero length arrays vs. pointers

    0 讨论(0)
  • 2020-12-17 21:05

    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.

    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.

    0 讨论(0)
  • 2020-12-17 21:06

    Speaking for C (and probably also C++ in this case), defining a zero-length array is undefined behavior, so GCC probably does this because a) nothing's stopping it, and b) it prevents errors like the ones you're trying to avoid.

    0 讨论(0)
  • 2020-12-17 21:13

    Zero sized array are only legal in C as the last element of atruct. Anything else is pointless.

    0 讨论(0)
  • 2020-12-17 21:16

    Zero-length arrays do not exist in C++. However if they did, here is how you could handle the case:

    template <bool B, typename T>
    struct disable_if;
    
    template <typename T>
    struct disable_if<false, T>
    {
        typedef T type;
    };
    
    template <class T, size_t N>
    typename disable_if<N == 0, void>::type foo(T(&c_array)[N])
    {
        std::cout << "inside template\n";
    }
    
    0 讨论(0)
提交回复
热议问题