FieryCod
FieryCod

Reputation: 1710

Sum function with list parameter C++11/C++14 style

I was watching the video on Youtube which was presenting a various features of a new standard (C++11, C++14).

I know that in C was a opportunity to create a variadic functions like that:

#include <stdarg.h>
#include <stdio.h>

double average(int count, ...)
{
    va_list ap;
    int j;
    double sum = 0;

    va_start(ap, count); /* Requires the last fixed parameter (to get the address) */
    for (j = 0; j < count; j++) {
        sum += va_arg(ap, int); /* Increments ap to the next argument. */
    }
    va_end(ap);

    return sum / count;
}

int main(int argc, char const *argv[])
{
    printf("%f\n", average(3, 1, 2, 3) );
    return 0;
}

The video shows the following example:

struct Sum
{
    template <typename T>
    static T sum(T n)
    {
        return n;
    }

    template <typename T, typename... Args>
    static auto sum(T n, Args ... rest) -> decltype(n + sum(rest...))
    {
        return n + sum(rest...);
    }
};

I use the second bunch of code like that:

int main()
{

    int suma = Sum::sum(1, 2, 3, 4, 5, 6);
    cout << suma;

    return 0;
}

And I found it fully workable so it is really great. But I did receive a warning:

(active) no instance of overloaded function "Sum::sum" matches the argument list

My question is : Which approach is better, and how can I get rid of warning in the second?

Upvotes: 1

Views: 631

Answers (1)

Jarod42
Jarod42

Reputation: 217950

First method is for C, second method is for C++ with type checking.

To fix your code in C++14, remove trailing return type: Demo

c++17 allows even folding expression:

template <typename ... Ts>
static auto sum(Ts...args)
{
    return (0 + ... + args);
}

Demo

Upvotes: 2

Related Questions