How to write a variadic template recursive function?

后端 未结 6 1200
走了就别回头了
走了就别回头了 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:38

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

    You get this error:

    error C2668: 'f': ambiguous call to overloaded function while trying to resolve f<3,>() call.
    

    This is because a variadic parameter pack can be given 0 arguments, so f<3> could work with template by "expanding" to template<3, >. However, you also have the specialization of template, so the compiler does not know which one to choose.

    Explicitly stating the first and second template arguments is a completely valid and good solution to this problem.


    When you try to change the base case to:

    template <>
    constexpr int f()
    {
        return 0;
    }
    

    You have a problem because functions cannot be specialized in that way. Classes and structs can be, but not functions.


    Solution #1: C++17 fold expression with constexpr

    template 
    constexpr int sum(Is... values) {
        return (0 + ... + values);
    }
    

    Solution #2: Use a constexpr function

    constexpr int sum() {
        return 0;
    }
    
    template 
    constexpr int sum(I first, Is... rest) {
        return first + sum(rest...);
    }
    

    Solution #3: Use Template Metaprogramming

    template 
    struct sum;
    
    template <>
    struct sum<>
        : std::integral_constant
    {};
    
    template 
    struct sum
        : std::integral_constant::value>
    {};
    

提交回复
热议问题