Udostępnij za pośrednictwem


Passing C++ Arrays by Value

Just in case you needed to, you can wrap an array into a struct/class and pass it by value to a function:

template<typename T, int N>
struct array {
    T value[N];
    T & operator[](int i) { return value[i]; }
};

template<typename T, int N>
void passByValue(array<T, N> a) {
    cout << "Value in function:" << endl;
    for (int i = 0; i < N; i++) a[i] = 1, cout << a[i] << endl; // prints 1's
}

int main() {
    const int N = 5;
    array<int, N > a;

    for (int i = 0; i < N; i++) a[i] = 0;

    passByValue(a);

    cout << "Value after function call:" << endl;
    for (int i = 0; i < N; i++) cout << a[i] << endl; // prints 0's

    return 0;
}

Comments

  • Anonymous
    August 07, 2009
    An good example about template :)

  • Anonymous
    August 07, 2009
    That's a real cool stuff. :-) Thanks for this post.

  • Anonymous
    August 07, 2009
    I have often used such a struct. With more extended use, I had to add a const version of operator[], to maintain array semantics. When I'm not passing the array by value, I would need a const version (constant reference) -- I shouldn't have to unbox the array:  const T& operator[](int i) const { return value[i]; } To use your output example:  template<typename T, int N>  void print(const array<T, N>& a) {    for (int i = 0; i < N; i++) cout << a[i] << endl;  } While we're at it, what if I want to pass the array to an STL algorithm (or another that uses iterators), or need to grab hold of the array itself?  T* operator&() { return value; }  T* const operator&() const { return value; } So you can do, say:  sort(&a, &a+N); It does look a bit ugly when you actually use it, but hey, this is C++. :-)

  • Anonymous
    August 08, 2009
    Take a look at boost:array. Dejan

  • Anonymous
    August 08, 2009
    @Remoun Great addition indeed. @djelovic I hope boost makes it to the standards in 2010