简体   繁体   中英

Deduce one dimension of 2D array at compile time

I have the following function:

template <int size>
double** writeArray(double input[size][2]) {

    double** Points = new double*[size];

    for (int i = 0; i < size; ++i) {
        Points[i] = new double[2];
    }

    for (int i = 0; i < size; ++i) {
        Points[i][0] = input[i][0];
        Points[i][1] = input[i][1];
    }

    return Points;
}

which writes from a double[size][2] array into a dynamically allocated double ** pointer.

Is there any way to deduce the size automatically, so that I could use it like that:

double** Points = writeArray(Test1);

instead of:

double** Points = writeArray<2>(Test1);

Yes! You can actually deduce both dimensions at compile-time. The idea is to write a template function that takes as its argument an array by reference . This prevents C++ from decaying the array type to a pointer type, which causes it to lose the array size. Here's an example:

template <typename T, size_t M, size_t N>
    void howBigAmI(T (&array)[M][N]) {
    std::cout << "You are " << M << " x " << N << " in size." << std::endl;
}

You should be able to adapt this to fit your needs if you'd like.

You should pass array by reference like:

template <int size>
double** writeArray(const double (&input)[size][2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM