passing an array as a const argument of a method in C++

后端 未结 4 1271
伪装坚强ぢ
伪装坚强ぢ 2020-12-16 19:14

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

4条回答
  •  没有蜡笔的小新
    2020-12-16 19:24

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

    template 
    void myMethod ( const int (& intArray) [N] )
    {
        std::cout << "Array of " << N << " ints\n";
        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 
    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.

提交回复
热议问题