incubator-stdcxx-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Travis Vitek" <Travis.Vi...@roguewave.com>
Subject RE: Forward iteration in variadic templates
Date Mon, 14 Jul 2008 20:52:15 GMT
 

Eric Lemings wrote:
>
>> Eric Lemings wrote:
>> 
>> Consider the following function:
>> 
>> template <class... Types>
>> void print (const Types&... values);
>> 
>> How would you define print() to iterate forward from 0..N, 
>> where N is sizeof... (Types), printing each argument X

I'm unsure about what you mean by iterate here. AFAIK, you can't iterate
over the elements in a parameter pack directly, everything is done with
recursion that terminates with one or more special cases.

>
>...and its corresponding index...
>
>> in the 
>> argument list (e.g. std::cout << X)?
>> 
>> Thanks,
>> Brad.
>> 
>

I don't know if this is what you had in mind, but it does what you ask.

$ cat q.cpp && g++ -std=gnu++0x q.cpp && ./a.out
#include <iostream>

template <class... _TTypes>
void print_impl (unsigned index, const _TTypes&... values);

template <class _TypeT>
void print_impl (unsigned index, const _TypeT& value)
{
    std::cout << index << ':' << value << '\n';
}

template <class _TypeT, class... _TTypes>
void print_impl (unsigned index, const _TypeT& value, const _TTypes&...
values)
{
    print_impl (index, value);
    print_impl (index + 1, values...);
}

template <class... _TTypes>
void print (const _TTypes&... values)
{
    print_impl (0, values...);
}

int main ()
{
  print (1, 'a', 3.14f, "hello");
  return 0;
}
0:1
1:a
2:3.14
3:hello

Mime
View raw message