如果在模板函数中通过const引用传递,数组不会衰减到指针 [英] array doesn't decay to pointer if passed by const reference in a template function

查看:144
本文介绍了如果在模板函数中通过const引用传递,数组不会衰减到指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自这个:

c ++将数组传递给函数问题

但是由于OP接受了答案,我想现在没有人会阅读它.

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

我在g ++上尝试了此代码.似乎数组在传递给该函数时不会衰减到指针(该函数返回正确的结果):

I tried this code on g++. It seems that the array does not decay to a pointer when passed to this function (the function returns the proper result):

#include <iostream>

template <typename T>
std::size_t size_of_array (T const & array)
{
   return sizeof (array) / sizeof (*array);
}

int main ()
{
    int a [5];
    std::cout << size_of_array (a) << '\n';
}

另一个用户(尖锐的牙齿)说他在VC ++ 10上具有相同的行为,但内联了.

Another user (sharptooth) said he have the same behavior on VC++ 10 with inlining off.

有人可以解释吗?谢谢.

Can somebody explain? Thanks.

推荐答案

数组衰减不仅会发生-仅当程序没有它就无法编译时才会发生.当您通过引用传递数组时,根本就不需要衰减.

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.

请注意,也可以编写函数模板而无需分割难看的sizeof表达式:

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;
}

当客户呼叫size_of_array时,模板机制会自动推导TN.

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

这篇关于如果在模板函数中通过const引用传递,数组不会衰减到指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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