0

Is it possible to split variadic parameter into list of items and access them? below you can see example of what I want to achieve - first piece, is standard, simple example of using variadic parameters

float sum()
{
    return 0;
}

template<typename ... Types>
float sum(float first, Types ... rest)
{
    return first + sum(rest...);
}

below, you can see what I'd like to do

template<typename ... Types>
float func(int first, Types ... rest)
{
    std::cout<<first<<std::endl;
    for(auto item : rest)
             cout<<rest<<std::endl;
}

I know I can print and do things recursively, but is there way to access params w/o recursion?

encore leet
  • 55
  • 1
  • 1
  • 8

1 Answers1

2
#include <iostream>
#include <string>

template<class...T>
void printall(const T&...t)
{
    using expander = int[];
    auto sep = "";
    (void) expander { 0, ((std::cout << sep << t), sep = ", ", 0)... };
    std::cout << std::endl;
}

using namespace std;

auto main() -> int
{
    auto s = "World"s;
    auto p = "Hello";
    printall(p, s, 5.0, 6);
    return 0;
}

expected output:

Hello, World, 5, 6
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • Is the evaluation order in `{ 0, ((std::cout << sep << t), sep = ", ", 0)... }` left-to-right or undefined? – Andrey Nasonov Sep 29 '15 at 23:51
  • @AndreyNasonov, It's left-to-right in a braced initializer (*Within the initializer-list of a braced-init-list, the initializer-clauses, including any that result from pack expansions, are evaluated in the order in which they appear*). The comma operator also defines a special fixed order of evaluation (In the section on the comma operator: *A pair of expressions separated by a comma is evaluated left-to-right*) – chris Sep 30 '15 at 00:21