c++boostboost-multi-array

Can you call a function using different sized boost::multi_arrays?


I am trying to build a function to write multidimensional arrays to the file system. In order to keep it compact I would like to just create one function for different sized multi_arrays.

typedef boost::multi_array<int, 2> Array2D;
typedef boost::multi_array<int, 3> Array3D;
typedef boost::multi_array<int, 4> Array4D;
typedef boost::multi_array<int, 5> Array5D;

void writeArrayToFile(boost::multi_array_base_type array){
    // do things with array
}

void main(){
    Array2D myArray2D; // + fill array
    writeArrayToFile(myArray2D);

    Array3D myArray3D; // + fill array
    writeArrayToFile(myArray3D);
    //... and so on
}

is there such a thing as boost::multi_array_base_type or are there other ways to accomplish this?


Solution

  • Templates are your friends in c++. You solve problems with templates. Learn to love them:

    template<std::size_t N>
    void writeArrayToFile(const boost::multi_array<int, N>& array) {
        // do things with array
    }
    

    You can then call your function like that and let the compiler deduce the size:

    writeArrayToFile(myArray2D);
    writeArrayToFile(myArray3D);
    

    If you like, you can even deduce the element type:

    template<typename T, std::size_t N>
    void writeArrayToFile(const boost::multi_array<T, N>& array) {
        // do things with array
    }