Is it possible to create and initialize an array of values using template metaprogramming?

前端 未结 7 759
悲&欢浪女
悲&欢浪女 2020-12-04 22:20

I want to be able to create an array of calculated values (let\'s say for simplicity\'s sake that I want each value to be the square of it\'s index) at compile time using t

7条回答
  •  难免孤独
    2020-12-04 23:01

    It's called Static Table Generation in metaprogramming.

    #include 
    
    const int ARRAY_SIZE = 5;
    
    template 
    class Table : public Table
    {
    public:
        static const int dummy;
    };
    
    template 
    class Table
    {
    public:
        static const int dummy;
        static int array[N];
    };
    
    template 
    const int Table::dummy = Table::array[I] = I*I + 0*Table::dummy;
    
    template 
    int Table::array[N];
    
    template class Table;
    
    int main(int, char**)
    {
        const int *compilerFilledArray = Table::array;
        for (int i=0; i < ARRAY_SIZE; ++i)
            std::cout<

    We use explicit template instantiation and a dummy variable to force the compiler to fill the array with index squares. The part after I*I is the trick needed to recursively assign each array elements.

提交回复
热议问题