How to write a variadic template recursive function?

后端 未结 6 1198
走了就别回头了
走了就别回头了 2020-12-09 03:39

I\'m trying to write a variadic template constexpr function which calculates sum of the template parameters given. Here\'s my code:

template<         


        
6条回答
  •  [愿得一人]
    2020-12-09 04:27

    Your base case was wrong. You need a case for the empty list, but as the compiler suggests, your second try was not a valid template specialization. One way to define a valid instantiation for zero arguments is to create an overload that accepts an empty list

    template
    constexpr int f()
    {
        return 0;
    }
    template
    constexpr int f()
    {
        return First + f();
    }
    int main()
    {
        f<1, 2, 3>();
        return 0;
    }
    

    EDIT: for completeness sake also my first answer, that @alexeykuzmin0 fixed by adding the conditional:

    template
    constexpr int f()
    {
        return sizeof...(Rest)==0 ? First : First + f();
    }
    

提交回复
热议问题