传递数组作为C ++中的方法的const参数 [英] passing an array as a const argument of a method in C++

查看:481
本文介绍了传递数组作为C ++中的方法的const参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够传递一个const数组参数到C ++中的方法。

I would like to be able to pass a const array argument to a method in C++.

我知道当你传递数组到方法时,

I know that when you pass an array to method it is the same than passing a pointer to the first item of the array so an easy way is to use the pointer.

void myMethod(int * const inTab)

但是有一个数组有时会更好,你可以写出数组的大小。

But having an array is sometimes better, you can write the size of the array for instance.

推荐答案

您可以使用数组大小​​的模板: http://ideone.com/0Qhra

You can use a template taking the array size: http://ideone.com/0Qhra

template <size_t N>
void myMethod ( const int (& intArray) [N] )
{
    std::cout << "Array of " << N << " ints\n";
    return;
}

编辑:
避免代码膨胀的一种可能方法是有一个函数,它接受一个指针和一个实际工作的大小:

A possible way to avoid code bloat would be to have a function that takes a pointer and a size that does the actual work:

void myMethodImpl ( const int * intArray, size_t n );

和一个调用它的简单模板,很容易被内联。

and a trivial template that calls it, that will easily be inlined.

template <size_t N>
void myMethod ( const int (& intArray) [N] )
    { myMethodImpl ( intArray, N ); }

当然,你必须找到一种方法来测试,但你确实得到安全和易用的。即使在不是这样的情况下,您可以获得相对较小的成本的好处。

Of course, you'ld have to find a way to test that this is always inlined away, but you do get the safety and ease of use. Even in the cases it is not, you get the benefits for relatively small cost.

这篇关于传递数组作为C ++中的方法的const参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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