Home > Enterprise >  How to pass any constexpr function as a parameter to constexpr array computation?
How to pass any constexpr function as a parameter to constexpr array computation?

Time:12-28

I struggle to pass any constexpr function as a parameter to the constexpr array computation.

How I would do this in a common C (not constexpr, just to show what I want)

float calcAdd2(float a) {
    return a   a;
}
float calcPow2(float a)
{
    return a * a;
}
template <class Func> 
auto calcArrArithmetic(int size, Func func) {
    float result[size]; //it’s common C   yet, so no std::array
    for (auto i = 0; i < size; i  ) {
        result[i] = func(i);
    }
    return result;
}
const static auto CALC_FIRST_10_ADD2 = calcArrArithmetic(10, calcAdd2);
const static auto CALC_FIRST_10_POW2 = calcArrArithmetic(10, calcPow2);

However, it's not that simple in constexpr. I started with plain array computation

template <std::size_t... I>
std::array<float, sizeof...(I)> fillArray(std::index_sequence<I...>) {
    return std::array<float, sizeof...(I)>{
        calcAdd2(I)...
    };
}
template <std::size_t N>
std::array<float, N> fillArray() {
    return fillArray(std::make_index_sequence<N>{});
}
static const auto CALC_FIRST_10_ADD2 = fillArray<10>();

Link. It worked. Now how to generalize calcAdd2 to be not only calcAdd2, but any constexpr function I would like to? My goal looks like:

static const auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2);
static const auto CALC_FIRST_10_POW2 = fillArray<10>(calcPow2);

EDIT: Answer to the question by madhur4127.

CodePudding user response:

Here's the simplified version of your code that does what you want:

constexpr float calcAdd2(float a) { return a   a; }

constexpr float calcPow2(float a) { return a * a; }

template <std::size_t N, typename Func>
constexpr auto fillArray(Func&& func) {
    std::array<float, N> ret{};
    for(unsigned i=0;i<N;  i) {
        ret[i] = func(i);
    }
    return ret;
}

constexpr auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2);
  • Related