Question

Been thinking about these questions for a while now but couldn't come up with an idea on how to do it.

Lets say I have a function like:

double sum( int param1 , double param2 , [ optional... ] )
{
     return param1 + param2;
}

Now I want

Q1: optional parameters

Q2: unlimited amount of optional parameters without having to declare them all ofc.

Q3: use of int and double values in those optional parameters

Thanks in advance :)

Was it helpful?

Solution

If you are familiar with c++11, there is a new concept introduced called variadic templates; which in essence allows one to create functions like you have mentioned which can take a varied amount of arguements.

The syntax for declaring such function looks like:

template <typename ... Types>
void someFunc(Types ...args) {}

Another option is to use an std::initializer_list along with std::accumulate to achieve this since you already know the types of the variables you will be using. An example using your program is this:

#include <iostream>
#include <initializer_list>
#include <numeric>
using namespace std;

double sum( initializer_list<double> vals ) {

    return accumulate(vals.begin(), vals.end(), 0.0);
}

int main() {
    // your code goes here
    cout << sum({2, 3, 4.6, 5, 6, 74.322, 1}) << endl;
    return 0;
}

OTHER TIPS

You want to use Variadic function.

One example shown there is quite easy to understand, which will compute the average of an arbitrary number of arguments. Note that the function does not know the number of arguments or their types.

#include <stdarg.h>

double average(int count, ...)
{
    va_list ap;
    int j;
    double tot = 0;
    va_start(ap, count); /* Requires the last fixed parameter (to get the address) */
    for(j = 0; j < count; j++)
        tot += va_arg(ap, double); /* Increments ap to the next argument. */
    va_end(ap);
    return tot / count;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top