C ++ Constexpr Member Type Template

I want to create a template class with an element that is a constexpr array. Of course, an array needs a different initialization depending on the type, but I cannot declare an array without initializing it. The problem is that I do not know the values โ€‹โ€‹of the array before the specialized 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 to initialize A :: a [] to B correctly?

+6
source share
1 answer

Each problem can be solved by adding another layer of indirection (except for too many indirect ones):

 // 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; }; 
+6
source

Source: https://habr.com/ru/post/978084/


All Articles