mercredi 25 avril 2018

Sum of squares using variadic templates

I am trying to find the sum of squares using variadic templates. The input parameters are the numbers whose sum of squares need to be calculated. Ex: foo(2, 3, 4) should return a value of 27 (which is 2+(9+16)). My template function looks as follows:

template<typename T>
T foo(T args)
{
    return args*args;
}

template <typename T, typename... A>
T foo(T first, A... args)
{
    return first+foo(pow(args,2)...);
}

However the result of this function seems to be 261 which was not what I expected.

Aucun commentaire:

Enregistrer un commentaire