Pregunta

Summary

What can I do if a function of an external library expect a non-const pointer (double *) but it is known that the values of it remains the same so according to const correctness I should pass a const pointer (const double *)?

The situation

I'd like to create a function that calculates the auto-correlation of a vector but unfortunately it seems that fftw3 (which is a C API) doesn't care about const correctness. The function I'd like to call is:

fftw_plan fftw_plan_dft_r2c_1d(int n0,
                                    double *in, fftw_complex *out,
                                    unsigned flags);

And the code I'd like to create:

vector<double> autocorr(const vector<double>& data)
{
    vector<double> ret(data.size(), 0);
    // prepare other variables
    fftw_plan a = fftw_plan_dft_r2c_1d(size, &data.front(), tmp, FFTW_ESTIMATE);
    // do the rest of the work
    return ret;
}

Of course, this will not work because the argument of my function is const vector<double>& data so I can't call &data.front(). What is the most appropriate solution to keep the const-correctness of my code?

¿Fue útil?

Solución

If you're confronted with a C API that promises more than it shows with respect to const-correctness, it is time to const_cast:

vector<double> autocorr(const vector<double>& data)
{
    vector<double> ret(data.size(), 0);
    // prepare other variables
    fftw_plan a = fftw_plan_dft_r2c_1d(size, const_cast<double*>(&data.front()), tmp, FFTW_ESTIMATE);
    // do the rest of the work
    return ret;
}

Also note this sentence in the documentation:

in and out point to the input and output arrays of the transform, which may be the same (yielding an in-place transform). These arrays are overwritten during planning, unless FFTW_ESTIMATE is used in the flags.

Since you're using the FFTW_ESTIMATE flag, you should be fine in this case.

The reason FFTW developers decided not to duplicate this function for the sake of const is that in C, const isn't at all a big deal, and FFTW is a C library.

Otros consejos

First file a bug report against the library, then const_cast away the const-ness of &data.front(), for example const_cast<double*>(&data.front())

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top