Templated Sum(Args...) variadic function doesn't compile

I used static struct member trick to enforce 2nd pass compilation and still get an error:

struct S
{
    template <typename T>
    static T Sum(T t) {
        return t;
    }

    template <typename T, typename ... Rest>
    static auto Sum(T t, Rest... rest) -> decltype(t + Sum(rest...) )
    {
        return t + Sum(rest...);
    }
};

int main()
{
    auto x = S::Sum(1,2,3,4,5);
}

main.cpp:17:14: No matching function for call to 'Sum'


Even using clang 4.0 the compilation fails.

I managed to compile it using decltype(auto) (solely auto will work too) instead of the explicit tail return type.

struct S
{
    template <typename T>
    static T Sum(T t) {
        return t;
    }

    template <typename T, typename ... Rest>
    static decltype(auto) Sum(T t, Rest... rest) 
    {
        return t + Sum(rest...);
    }
};

I think that the compiler is not able to the deduce the type cause the deduction depends only by a recursive return statement.

More info here

链接地址: http://www.djcxy.com/p/96968.html

上一篇: 当使用CSS动态改变页面高度时,将页脚保留在页面底部

下一篇: 模板化Sum(Args ...)可变参数函数不能编译