1

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.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • 3
    Not possible and doesn't make any sense. Why? – Bryan Chen Aug 26 '14 at 03:10
  • 2
    Are you wanting to [curry](http://en.wikipedia.org/wiki/Currying) the function? – Cornstalks Aug 26 '14 at 03:14
  • @BryanChen: With C++11 (or rather C++14), lots of things are now possible. – Nawaz Aug 26 '14 at 03:20
  • void get(int a, char b, int c, (float d = afunction(int i)), (int e = afunction(int j)), (char f = afunction(int j))); You can call the function directly within the parameter as long as these functions returns a name type. – Juniar Aug 26 '14 at 03:35

2 Answers2

8

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • With all due respect sir i'm a starter. I've just started learning OOP in C++ and i came across thee topic of function overloading. I don't really know about it. what i do know is that there is a simple way by using : operator in the function call with the variable name. I dont know the syntax but it can be done using :. Please correct me if iam wrong.... – Hasan Afzal Aug 26 '14 at 03:41
  • 1
    @HasanAfzal: I don't know which *"simple way"* you're talking about. The above answer provides simple solution as well. Just read about [Lambda in C++](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) and function overloading. That is it. – Nawaz Aug 26 '14 at 03:50
0

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`.
R Sahu
  • 204,454
  • 14
  • 159
  • 270