传递一个数组在C的方法的常量参数++ [英] passing an array as a const argument of a method in C++

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

问题描述

我希望能够常量数组参数传递给方法在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;
}

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

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

当然,you'ld必须找到一种方法来测试,这是始终走内联,但你得到使用的安全性和易用性。即使是在它不是的情况下,将得到相对较小的成本的好处。

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的方法的常量参数++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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