本文介绍了将数组作为 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 参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:15