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

前端 未结 7 758
悲&欢浪女
悲&欢浪女 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:09

    I'm not sure whether you want to see it done or find a library that will just do it for you. I assume the former.

    template
    struct SqArr {
        static inline void fill(int arr[]) {
            arr[N-1] = (N-1)*(N-1);
            SqArr::fill(arr);
        }
    };
    
    template<>
    struct SqArr<0> {
        static inline void fill(int arr[]) { }
    };
    

    Now let's try to use this beast:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main(int argc, char* argv[])
    {
        int arr[10];
        SqArr<10>::fill(arr);
        cout << endl;
        copy(arr, arr+10, ostream_iterator(cout, "\t"));
        cout << endl;
        return 0;
    }
    

    Note (confession): This isn't compile-time computation. To motivate that you can try to change the fourth line from SqArr::fill(arr); to SqArr::fill(arr); so the recursion is infinite, and you will see this compiles fine (when the compiler should in fact recurse indefinitely, or complain about the infinite recursion).

提交回复
热议问题