Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c++ - Create static array with variadic templates

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...