mercredi 4 décembre 2019

How do I initialise a const array struct field with the output of a function?

I have a struct that contains a const array, and would like to initialise it to specific values upon construction. Unfortunately, its contents depend on several parameters which are passed into the constructor as parameters, and require a function to compute the contents of the array.

What I'd ideally like to do looks something like this:

struct SomeType {
    const unsigned int listOfValues[32];

    unsigned int[32] processParameters(unsigned int parameter) {
        unsigned int arrayValues[32];
        for(int i = 0; i < 32; i++) {
            arrayValues[i] = i * parameter;
        }
        return arrayValues;
    }

    SomeType(unsigned int parameter) : listOfValues(processParameters(parameter)) {

    }
};

Of course there are several issues here (returning an array from a function is not possible, data type mismatches, etc). However, is there any way this is possible?

I've seen other similar questions suggest using a std::vector for this, but the heap allocation(s) this incurs is something my performance budget can't afford.

Aucun commentaire:

Enregistrer un commentaire