Hasan Afzal
Hasan Afzal

Reputation: 39

How can you give a function one parameter at a time?

For example, I have a function:

void get(int a, char b, int c, float d, int e, char f)

I want to give the function just d, e and f. How can I pass them as parameters.

Just the three of them.

Upvotes: 1

Views: 172

Answers (2)

R Sahu
R Sahu

Reputation: 206717

If you are willing to switch the parameters of the function and give default values to a, b, and c, you can do that.

void get( float d, int e, char f, int a = 10, char b='\n', int c=16);

Then, you can call the function with values of just d, e, and f.

get(5.0f, 20, '\t');

The above call is equivalent to

get(5.0f, 20, '\t', 10, '\n', 16);
                    ^^^^^^^^^^^^^^ These are the default value of `a`, `b`, and `c`.

Upvotes: 0

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361712

Write an overload as shown below:

auto get(float d, int e, char f) -> std::function<void(int, char, int)>
{
   return [=](int a, char b, int c) { get(a,b,c, d,e,f); };
}

That is, this overload takes d, e, f only and returns a callable entity which takes rest of the arguments — this callable entity eventually invokes your get() function.

You can use it as:

auto partial_get = get(d,e,f); //pass d, e, f
//code
partial_get(a,b,c); //invoke partial_get() passing rest of the arguments!

Here partial_get is a callable enity which you can invoke anytime passing the rest of the arguments — partial_get eventually invokes your get() function passing all the required arguments.

Upvotes: 8

Related Questions