Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 272
barney Avatar asked Aug 04 '17 09:08

barney


1 Answers

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

like image 62
Davide Spataro Avatar answered Nov 15 '22 05:11

Davide Spataro