samedi 23 décembre 2017

Fibonacci and 'if constexpr'

Please consider this code:

template<int nIndex>
int Fibonacci()
{
    if constexpr (nIndex == 0) return 0;
    if constexpr (nIndex == 1) return 1;

    static_assert(nIndex >= 0, "Invalid index passed to Fibonacci()");
    return Fibonacci<nIndex - 1>() + Fibonacci<nIndex - 2>();
}

int main()
{
    Fibonacci<3>(); // 2
    //Fibonacci<-1>();  // Fires assertion 

    return 0;
}

When I run this in VS2017, the compiler outputs:

error C2338: Invalid index passed to Fibonacci()
note: see reference to function template instantiation 'int Fibonacci<-1>(void)' being compiled
note: see reference to function template instantiation 'int Fibonacci<1>(void)' being compiled
note: see reference to function template instantiation 'int Fibonacci<3>(void)' being compiled

This is not what I expect; I expect the result to be 2. Am I using if constexpr incorrectly here?

Furthermore, I don't understand the compiler's diagnostic message.

Fib(3) = Fib(2)              + Fib(1)
       = Fib(1) + Fib(0)
       = 1      + 0          + 1
       = 2

So why is the compiler thinking that Fib(-1) is being called?

Aucun commentaire:

Enregistrer un commentaire