21

The following code is legal in C++11.

template<int... N>
std::tuple<decltype(N)...> f()
{
    return std::make_tuple(7 + N...); 
}

What does it mean?

rubenvb
  • 74,642
  • 33
  • 187
  • 332
xmllmx
  • 39,765
  • 26
  • 162
  • 323

1 Answers1

25

First of all, look at the template parameters: template <int ... N>. Even though a variable number of template arguments can be given to f, all of them must be of type int.

Now when you use f<t1, t2, ..., tn>, the parameter unpacking (7 + N...) will follow the pattern 7 + N and expand to

7 + t1, 7 + t2, 7 + t3, ..., 7 + tn

Therefore you end up with a tuple which contains each of your template arguments increased by seven. The details can be found in section 14.5.3 Variadic templates [temp.variadic].

3. A pack expansion consists of a pattern and an ellipsis, the instantiation of which produces zero or more instantiations of the pattern in a list [...].

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 1
    [Live example](http://coliru.stacked-crooked.com/a/239fe332227e245b). Note the `-std=c++1y`. – rubenvb Jul 09 '14 at 07:52
  • @rubenvb: Noticed it beforehand, but didn't think about the automatic type deduction that much (too much Haskell lately). But now that I think about it, is it actually possible to create a function with the same template parameters and type in C++11 without sacrificing kittens? – Zeta Jul 09 '14 at 08:11
  • @rubenvb: I see myself out. I knew there was something like `decltype`, but I haven't used templates meta programming in ages. Two hours of sleep isn't enough anymore :D. – Zeta Jul 09 '14 at 08:16