c++templatesvariadic-templatesreturn-type-deduction

The variadic template with automatic return type argument deduction


I implemented simple code to add all the numbers together, but when inserting one floating number everything gets weird!

How to analyze the behavior of the compiler to deduce the return type?

#include <iostream>

template <typename N>
auto summer(N n)
{
    return n;
}

template <typename N, typename... Args>
auto summer(N n, Args... args)
{
    return n + summer(args...);
}

int main()
{
    printf("add: %d \n", summer(4, 34.1, 13, 14, 15, 22)); // Print 22 ?!??!? return last number.
    printf("add: %d \n", summer(4, 34.1, 13, 14, 15, 20)); // Print 20 ?!!?!? return last number.
    printf("add: %f \n", summer(4, 34.1, 13, 14, 15, 20)); // It's true 100.1000 ?
}

Solution

  • Problem is that return type of summer() is double, but you are printing it with %d. Result is similar to when you run a code like this:

    printf("%d", 100.1);
    

    This is UB (Undefined Behavior). Quote from cpp ref:

    If any argument after default conversions is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by format, the behavior is undefined.