dimanche 21 octobre 2018

Using meta-programming to calculate the log2 but `compilation terminated`

I'm new to TMP and I wrote a program using meta-programming to calculate the log2. I wrote a template struct power2 to calculate the power, a template class log2arr with an array in it to save the result, and a embedded template struct log2 to calculate log2 values.

#include <iostream>

template <int i>
struct power2
{
    enum
    {
        value = (1 << i)
    };
};

template <int n>
class log2arr
{
    int arr[n];

    template <int i>
    struct log2
    {
        log2<i - 1> _arr;
        enum
        {
            value = log2<i - 1>::value + (power2<log2<i - 1>::value>::value == i)
        };
        void print()
        {
            _arr.print();
            std::cout << value << std::endl;
        }
        void set()
        {
            _arr.set();
            arr[i] = value;
        }
    };

    template <>
    struct log2<1>
    {
        enum
        {
            value = 1
        };
        void print() {}
        void set() {}
    };

  public:
    int *getArr()
    {
        log2<n>().set();
        return arr;
    }
};

int main()
{
    log2arr<4> a = log2arr<4>();
    for(auto i : a.getArr()){
        cout << i;
    }
}

But the compiler only told me compilation terminated.

What does it mean? How can I solve it?

Any help would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire