[英]How to pass any constexpr function as a parameter to constexpr array computation?
我很難將任何 constexpr function 作為參數傳遞給 constexpr 數組計算。
我將如何在常見的 C++ 中執行此操作(不是 constexpr,只是為了展示我想要的)
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);
然而,在 constexpr 中並沒有那么簡單。 我從普通數組計算開始
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>();
關聯。 有效。 現在如何將 calcAdd2 概括為不僅是 calcAdd2,而且是我想要的任何 constexpr function? 我的目標看起來像:
static const auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2);
static const auto CALC_FIRST_10_POW2 = fillArray<10>(calcPow2);
編輯:回答madhur4127的問題。
這是您的代碼的簡化版本,可以執行您想要的操作:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.