Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a function to each component of a variadic list and return a variadic list?

The following didactic example illustrates my problem :

#include <iostream>
#include <cmath>

template<class Function, class... Args>
double apply(Function f, Args... args)
{
    return f(args...);
}

template<class Function, class... Args>
double applybis(Function f, Args... args)
{
    return f(std::sin(args...));// <- How to apply a function to 
                                // each variadic parameter and 
                                // return a modified variadic list ?
}

int main(int argc, char* argv[])
{
    std::cout<<apply(static_cast<double(*)(double)>(std::sin), 3.)<<std::endl;
    return 0;
}

How to "transform" a variadic list by applying a function to each component and return a modified variadic list ? (Is there a way to write the applybis function without modifying its current signature ?)

like image 564
Vincent Avatar asked Nov 20 '12 19:11

Vincent


People also ask

How do you write a variadic function?

The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter. This enables access to variadic function arguments. *argN* is the last fixed argument in the variadic function. This one accesses the next variadic function argument.

How do you declare a variadic function in C++?

Variadic functions are functions (e.g. std::printf) which take a variable number of arguments. To declare a variadic function, an ellipsis appears after the list of parameters, e.g. int printf(const char* format...);, which may be preceded by an optional comma.

What symbols are used in a function declaration to indicate that it is a variadic function?

A function with a parameter that is preceded with a set of ellipses ( ... ) is considered a variadic function. The ellipsis means that the parameter provided can be zero, one, or more values.

What is variadic function in Golang?

A variadic function is a function that accepts a variable number of arguments. In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature.


1 Answers

Here you go:

return f(std::sin(args)...);

That is, ... should come after (args).

It expands/unpacks to this form:

return f( std::sin(arg0), std::sin(arg1), ......, std::sin(argN) );
like image 72
Nawaz Avatar answered Oct 14 '22 18:10

Nawaz