Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constexpr member of template type

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?

like image 479
barsan-md Avatar asked Nov 12 '14 12:11

barsan-md


1 Answers

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;
};
like image 136
Barry Avatar answered Oct 22 '22 05:10

Barry