Is this template<int ...> idea in C++ possible?

117 Views Asked by At

I'm trying to learn to implement template in C++. When I am changing my NTT (Number theoretic transform) code into one that uses template, which looks like this:

template <long long mod> struct NTT{
    int x = 0;
    NTT(){
        long long p = mod-1;
        while(!(p % 2)){
            p >>= 1;
            ++x;
        }       
    }   
    const static long long root_pw = 1 << x;
//(there is a function after this that also needs to read the value 'root_pw')
};

signed main()
{
    NTT<998244353> ntt1;
    vector<long long> a(ntt1::root_pw,0);
}

It tells me to make x static.

When I do that, it tells me to make x const, which beats the reason for x being there in the first place.

I use (GNU C++11) and my complier (Dev-C++ 5.11) set to configure (TDM-GCC 4.9.2 64-bit Release), if it helps.

I really want to make this work, but I don't know how.

This is probably stupidly easy, but just what I'm I missing?

Thank you in advance.

1

There are 1 best solutions below

2
On BEST ANSWER

You can replace the C++14 function

template <long long mod>
constexpr int f()
{
    int x = 0;
    long long p = mod-1;
    while(!(p % 2)){
        p >>= 1;
        ++x;
    }       
    return x;
}

by the C++11 version:

template <long long p>
constexpr int f2()
{
    return p % 2 ? 0 : 1 + f2<p / 2>();
}

template <long long mod>
constexpr int f()
{
    return f2<mod - 1>();
}

And so

template <long long mod>
struct NTT{
    constexpr static const long long root_pw = 1LL << f<mod>();

};

Demo