Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

passing an array as a const argument of a method in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...