array doesn't decay to pointer if passed by const reference in a template function

后端 未结 2 1966
庸人自扰
庸人自扰 2021-01-18 07:02

This question comes from this one:

c++ pass array to function question

but since the OP accepted an answer I guess nobody will read it now.

I tried t

相关标签:
2条回答
  • 2021-01-18 07:42

    Array decay doesn't just happen -- it only happens when the program would fail to compile without it. When you pass an array by reference, there simply is no need for decay to kick in.

    Note that the function template can also be written without dividing ugly sizeof expressions:

    template <typename T, std::size_t N>
    std::size_t size_of_array(T (&array)[N])
    {
        return N;
    }
    

    When a client calls size_of_array, T and N are automatically deduced by the template machinery.

    0 讨论(0)
  • 2021-01-18 07:51

    You haven't written the function to accept a pointer, you've written it to accept a const reference to exactly the type of argement that's passed to it. Pointer decay only happens if you try to assign to a pointer the value of an array.

    0 讨论(0)
提交回复
热议问题