I want to create a template class with a member which is a constexpr array. The array needs, of course, a different initialization depending on the type it is but I cannot declare the array without initializing it. The problem is that I don't know the values of array until template specialization.
//A.hpp
template<typename T>
class A {
public:
static constexpr T a[];
constexpr A() {};
~A() {};
}
//B.hpp
class B: public A<int> {
public:
constexpr B();
~B();
};
//B.cpp
template<>
constexpr int A<int>::a[]={1,2,3,4,5};
B::B() {}
B::~B() {}
How can I properly initialize A::a[] in B?
Every problem can be solved by adding another layer of indirection (except too much indirection):
// no a[] here.
template <typename T> struct ConstArray;
template <>
struct ConstArray<int> {
static constexpr int a[] = {1, 2, 3, 4, 5};
int operator[](int idx) const { return a[idx]; }
};
template <typename T>
class A {
static constexpr ConstArray<T> a;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With