Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static const array initialization in template class

I have the following template class:

template <unsigned N>
class XArray {
  static const int Xdata[N];
};

I want to initialize the static const array for each XArray<N> I used, for example, let XArray<N>::Xdata = {1, 2, 3, ..., N}. How to make it?

like image 996
Oliver Q Avatar asked Oct 21 '22 05:10

Oliver Q


2 Answers

you declared a static const int array in your class,so you must define the static member out of the class declaration,just like this:

template<unsigned N>
class XArray
{
public:
static const int array[N];
};
template<unsigned N>
const int XArray<N>::array[N] = {1,2,3,4,5};

But something you must pay attention to is that: when you use this template you must make sure that the "N" bigger than the number of your initialized array;

like image 134
minicaptain Avatar answered Oct 24 '22 12:10

minicaptain


EDIT:

It seems someone have already provided the solution for your problem in other question, and the answer is quite the same as mine.

Also, for more generic answer, you can check out answers to this question.


Code

If you don't mind using C++11 features, then variadic templates may come handy:

template <unsigned ...Args>
struct XArrayData
{
    static const int Values[sizeof...(Args)];
};

template<unsigned N, unsigned ...Args>
struct _XArrayGenerator
{
    typedef typename _XArrayGenerator<N - 1, N, Args...>::Xdata Xdata;
};

template<unsigned ...Args>
struct _XArrayGenerator<1, Args...>
{
    typedef typename XArrayData<1, Args...> Xdata;
};

template<unsigned N>
struct XArray
{
    typedef typename _XArrayGenerator<N>::Xdata Xdata;
};

template <unsigned ...Args>
const int XArrayData<Args...>::Values[sizeof...(Args)] = { Args... };

Explanation

XArray template struct takes the number of array elements as a template parameter (N). In the compilation time, it uses _XArrayGenerator to generate template paremeter list with N consecutive numbers. It begins with the number N, and then recursively uses itself until it reaches 1. At this point, the template parameter list looks like this:

1, 2, ..., N

The last thing to do is to pass these parameters to XArrayData. The last line of the code (definition of the actual array) uses the parameters to initialize the array.

Usage

for (int i = 0; i < 3; ++i)
    cout << XArray<3>::Xdata::Values[i] << endl;

Output:

1
2
3
like image 33
podkova Avatar answered Oct 24 '22 10:10

podkova