2

With this code:

static unsigned count = 0;

template<typename... T>
auto sum(T... args)
{
    ++count;
    return (... + args);
}

int main (void)
{
    std::cout << sum(12, 32, 32, 12, 4, 3, 43, 432) << std::endl;
    std::cout << "TIME: " << count << std::endl;
}

Output is:

$> ./program.out
570
TIME: 1

Why is count equals to 1? I expected count to be 8. Is sum template function called only once?

Holt
  • 36,600
  • 7
  • 92
  • 139
Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32

2 Answers2

2

Is sum template function call once ?

Yes, it won't be called recursively. Instead, the expression is expanded for fold expression.

The instantiation of a fold expression expands the expression e as follows:

...
2) Unary left fold (... op E) becomes (((E1 op E2) op ...) op EN)
...

(where N is the number of elements in the pack expansion)

You might want to put ++count into the fold expression, e.g.

template<typename... T>
auto sum(T... args)
{
    return (... + (++count, args));
}

As @Xatyrian pointed, its value is just same as the number of elements in the pack expansion, which could be taken by sizeof... too.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 5
    If the goal is to count the number of parameters in the template pack, i would prefer using `sizeof...(T)` as presented in [this SO thread](https://stackoverflow.com/questions/12024304/c11-number-of-variadic-template-function-parameters) – Xatyrian Jan 03 '20 at 09:06
  • When i write `(++count, args)`, Compiler(__GCC9__) give me a warning _warning: multiple unsequenced modifications to 'count'_. – Ghasem Ramezani Jan 03 '20 at 09:13
  • @GhasemRamezani Yes, the evaluation order of multiple `++count` would be unsequenced here; I think it's fine for this case. – songyuanyao Jan 03 '20 at 09:16
0

If you wanted to call sum multiple times, you could do so recursively:

static unsigned count = 0;

template <typename T>
auto sum(T t)
{
    ++count;
    return t;
}

template <typename T, typename... Ts>
auto sum(T t, Ts... ts)
{
    ++count;
    return t + sum(ts...);
}
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
  • No, I am new to `C++ Templates` and my goal is to know when we use `...` in function body for use remaining arguments, Is recursive function call or not. – Ghasem Ramezani Jan 03 '20 at 09:27