Unexpected output in variadic template C++11

67 Views Asked by At

I wrote a very simple code to add numbers in pair using variadic templates. The expected output for the given test case should be 6 but i see 3. I also tried debugging but nothing looks wrong. Why is the output 3 but not 6?

template<typename T>
bool pairwise_sum(const T&first, const T&second) 
{
    return (first + second); 
}

template<typename T, typename... Args>
T pairwise_sum(const T&first, const T&second, Args... args)
{
    return (first + second) + pairwise_sum(args...);
}

void test()
{
    auto sumInPair = pairwise_sum(1, 1, 2, 2);
}

Also another question i have is since all the code is generated at compile time. Will the operator precedence matter? For e.g. if the function was something like :

template<typename T>
bool pairwise_sum_10fold(const T&first, const T&second) 
{
    return 10 * ( (first + second));
}

template<typename T, typename... Args>
T pairwise_sum_10fold(const T&first, const T&second, Args... args)
{
    return 10 * (first + second) + pairwise_sum_10fold(args...);
}

In this case does it matter whether i put return value in parenthesis as * has greater precedence than +?

P.S. I am using VS 2017 compiler. Thanks in advance.

0

There are 0 best solutions below