c++templatesexpand

C++ why my template expansion lead to compiler stack overflow?


I was trying template meta programming and writing a function to calculate power of base^re like 3^2=9

template<int N>
int Tpow(int base){return N==0?1:base*Tpow<N-1>(base);}
int main()
{
    int r3=Tpow<3>(2);
    return 0;
}

Just several lines, but it crashes both gcc and clang. Where did I get wrong? Thanks.


Solution

  • Solution: You have to specialize your template for N equal 0. Like:

    template<>
    int Tpow<0>(int base){return 1;}
    

    Now that you have this, you could also optimize your original template like so:

    template<int N>
    int Tpow(int base){return base*Tpow<N-1>(base);}
    

    because you know you handle the case of N equal 0.

    Explanation: Your compiler is basically doing this: It sees

    int r3=Tpow<3>(2);
    

    and makes a function for 3 as the template variable, like so

    int Tpow_3(int base){return 3==0?1:base*Tpow<3-1>(base);}
    

    and then it needs to make a function for 2 as template variable, like so

    int Tpow_2(int base){return 2==0?1:base*Tpow<2-1>(base);}
    

    and this goes on and on an on, because the compiler doesn't care about your 0==0?... yet.