This is follow-on from the post: Passing this pointer and arguments of class method to local lambda function at compile time.
Suppose that you want to use the result array of local constexpr
lambda inside a constexpr
method:
template<typename T, std::size_t N>
struct A {
std::array<T, N> arr;
constexpr A(std::array<T, N> arr) : arr(arr) {}
constexpr auto operator+(A rhs) const {
constexpr auto l = [](const auto& ta, const auto& ra) {
std::array<T, N> result;
result.fill(T{0});
for (std::size_t i = 0; i < N; i++) {
result[i] = ta[i] + ra[i];
}
return A(result);
};
constexpr auto result = l(arr, rhs.arr);
/* use result by calling another constexpr methods / functions */
return result;
}
};
template<typename ... T>
A(T...) -> A<T..., sizeof...(T)>;
int main() {
constexpr A a(std::array<int, 3>{1, 2, 3}),
constexpr A b(std::array<int ,3>{4, 5, 6});
constexpr A c = a + b;
return 0;
}
The compiler said that this
and rhs
are not constant expressions. How can I maintain constexpr-ness in this case?