I'm failing to programmatically initialize a static constexpr std::array
member.
This is a minimal example of my issue (for simplification size is known and small, thus initialization could be manual but I'd like to make the actual size a template non-type parameter, thus ruling out a manual initialization):
#include <array>
constexpr std::size_t N = 3;
using Mat = std::array<double, N * N>;
// OK, can initialize a free constexpr Mat
constexpr Mat InitEye() noexcept {
Mat TmpEye{0};
for (std::size_t r = 0; r < N; ++r) {
for (std::size_t c = 0; c < N; ++c) {
TmpEye[r * N + c] = (r == c) ? 1. : 0.;
}
}
return TmpEye;
}
// KO
class Wrapper {
private:
// KO cannot use it to initialize static constexpr member
static constexpr Mat WrappedInitEye() noexcept {
Mat TmpEye{0};
for (std::size_t r = 0; r < N; ++r) {
for (std::size_t c = 0; c < N; ++c) {
TmpEye[r * N + c] = (r == c) ? 1. : 0.;
}
}
return TmpEye;
}
public:
static constexpr Mat Eye = WrappedInitEye();
};
// also KO
class Wrapper2 {
public:
// OK in C++17, still KO in C++17 due to lack of constexpr access operator
static constexpr Mat Eye = [] {
Mat TmpEye{0};
for (std::size_t r = 0; r < N; ++r) {
for (std::size_t c = 0; c < N; ++c) {
TmpEye[r * N + c] = (r == c) ? 1. : 0.;
}
}
return TmpEye;
}();
};
int main() {
constexpr Mat Eye = InitEye();
constexpr Mat Eye2 = Wrapper::Eye;
return 0;
}
The closest answer I found is this one (thus the lambda version above).
Yet live example si showing two issues:
- Non lambda version never works:
\<source\>:32:46: error: 'static constexpr Mat Wrapper::WrappedInitEye()' called in a constant expression before its definition is complete
32 | static constexpr Mat Eye = WrappedInitEye();
- Lambda version does not work either in C++14, due to the lack of
constexpr
access function forstd::array
The non-lambda version gives this "uncomplete definition" error because:
- constexpr initializing static member using static function
- `static constexpr` function called in a constant expression is...an error?
But still, how can I implement a programmatic std::array
initialization with C++14?
static constexpr
function called in a constant expression is...an error? – Publican