Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There was an answer on stackoverflow (which I can't seem to find anymore) which demonstrated how a variadic template can be used in C++11 to create a static array at compile time:

template <class T, T... args> 
struct array_
{
    static const T data[sizeof...(args)];
};

template <class T, T... args> 
const T array_<T, args...>::data[sizeof...(args)] = { args... };

A recursive meta-function could be provided to instantiate array_ with any number of parameters, which will then be copied at compile time into the internal array. It's a useful way to create meta-functions for generating constant arrays at compile time.

However, one problem is that it depends on class template parameters to get the actual values to populate the array. This results in one major limitation: only integral constants can be used as value template parameters. So, you can't use this technique to generate arrays of custom types.

I tried to think of something to work around this limitation, but can't come up with anything. Is there any way to make this technique work with non-integral constants?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well, you can indeed populate a static array with custom types (i.e. classes) instances provided that they are constructable from integer types (or whatever other types one may provide as non template parameters and which I am not going enumerate here).

Just take look at the example bellow, which I believe is clear enough to be self explaining:

#include <iostream>

template<typename T>
class my_class
{
    public:
        my_class(T)
        {
            //construct
        }

        void print_something()
        {
            std::cout << "something
";
        }
};

template<class C, class T, T ... args>
struct array_
{
        static C data[sizeof...(args)];
};

template<class C, class T, T ... args>
C array_<C, T, args...>::data[sizeof...(args)] = {C(args)...};

int main()
{
    array_<my_class<int> , int, 1, 200, 0, 42>::data[2].print_something();
}

Note: compiled just fine under GCC 4.6


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...