6

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?

Barry
  • 286,269
  • 29
  • 621
  • 977
barsdeveloper
  • 930
  • 8
  • 28

1 Answers1

6

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;
};
Casey
  • 41,449
  • 7
  • 95
  • 125
Barry
  • 286,269
  • 29
  • 621
  • 977